extract date only from given timestamp in oracle s

2019-04-04 03:44发布

The following query:

select cdate from rprt where cdate <= TO_CHAR(sysdate, 'YYYY/MM/DD-HH24-MI-SS-SSSSS') and ryg='R' and cnum='C002';

return: 2013/04/27-10:06:26:794 as stored in the table.

I want to get the date only as : 27-04-2013 and get the number of days between the resul tdate and sysdate.

6条回答
Fickle 薄情
2楼-- · 2019-04-04 04:11

This is exactly what TO_DATE() is for: to convert timestamp to date.

Just use TO_DATE(sysdate) instead of TO_CHAR(sysdate, 'YYYY/MM/DD-HH24-MI-SS-SSSSS').

SQLFiddle demo

UPDATE:

Per your update, your cdate column is not real DATE or TIMESTAMP type, but VARCHAR2. It is not very good idea to use string types to keep dates. It is very inconvenient and slow to search, compare and do all other kinds of math on dates.

You should convert your cdate VARCHAR2 field into real TIMESTAMP. Assuming there are no other users for this field except for your code, you can convert cdate to timestamp as follows:

BEGIN TRANSACTION;
-- add new temp field tdate:
ALTER TABLE mytable ADD tdate TIMESTAMP;
-- save cdate to tdate while converting it:
UPDATE mytable SET tdate = to_date(cdate, 'YYYY-MM-DD HH24:MI:SS');

-- you may want to check contents of tdate before next step!!!

-- drop old field
ALTER TABLE mytable DROP COLUMN cdate;
-- rename tdate to cdate:
ALTER TABLE mytable RENAME COLUMN tdate TO cdate;
COMMIT;

SQLFiddle Demo

查看更多
Explosion°爆炸
3楼-- · 2019-04-04 04:12

try this type of format:

SELECT to_char(sysdate,'dd-mm-rrrr') FROM dual
查看更多
Melony?
4楼-- · 2019-04-04 04:16

Convert Timestamp to Date as mentioned below, it will work for sure -

select TO_DATE(TO_CHAR(TO_TIMESTAMP ('2015-04-15 18:00:22.000', 'YYYY-MM-DD HH24:MI:SS.FF'),'MM/DD/YYYY HH24:MI:SS'),'MM/DD/YYYY HH24:MI:SS') dt from dual
查看更多
Viruses.
5楼-- · 2019-04-04 04:17

Use the function cast() to convert from timestamp to date

select to_char(cast(sysdate as date),'DD-MM-YYYY') from dual;

For more info of function cast oracle11g http://docs.oracle.com/cd/B28359_01/server.111/b28286/functions016.htm#SQLRF51256

查看更多
霸刀☆藐视天下
6楼-- · 2019-04-04 04:17

If you want the value from your timestamp column to come back as a date datatype, use something like this:

select trunc(my_timestamp_column,'dd') as my_date_column from my_table;
查看更多
贼婆χ
7楼-- · 2019-04-04 04:21

This format worked for me, for the mentioned date format i.e. MM/DD/YYYY

SELECT to_char(query_date,'MM/DD/YYYY') as query_date 
FROM QMS_INVOICE_TABLE;
查看更多
登录 后发表回答