简体   繁体   中英

How to convert date in Oracle?

I have sql query in MySQL:

SELECT
   distinct 
   us.user_id as user_id, 
   us.ab_id,
   users.name,
   users.role,
   users.is_admin,
   DATE_FORMAT('2013-11-05T10:06:21+04:00', '%Y-%m') as month_m
FROM attach_offices as us
LEFT JOIN users ON users.id = user_id
WHERE us.`ab_id` = 999999999 and
 DATE_FORMAT('2013-11-05T10:06:21+04:00', '%Y-%m') between DATE_FORMAT(dt_begin, '%Y-%m') and DATE_FORMAT(`dt_end`, '%Y-%m')

How to convert it to Oracle 11g? I write something like this:

SELECT 
     distinct 
   attach_offices.user_id as user_id, 
   attach_offices.ab_id,
   users.name,
   users.role,
   users.is_admin,
   to_date('2013-11-05T10:06:21+04:00', 'YYYY-MM') as month_m       
FROM attach_offices 
LEFT JOIN users ON users.id = user_id
WHERE attach_offices.ab_id = 999999999 and
 to_date('2013-11-05T10:06:21+04:00', 'YYYY-MM') between to_date(to_char(dt_begin, 'YYYY-MM'), 'YYYY-MM') and to_date(to_char(dt_end, 'YYYY-MM'), 'YYYY-MM')

But it does not work. The problem in date, when i use 2013-11-05T10:06:21+04:00 it does not work but when i use 2013-11 it is work

Because TO_DATE will convert given STRING to DATE by format, you have specified.
DATE_FORMAT however formats DATE as specified.

So you have following options:
1. If you want to get desired DATE as some special crafted STRING , then you go with TO_CHAR(DATE, '<format>')
2. If you want to convert given STRING to DATE , you go with TO_DATE(string,'<format that describes string>') .
3. If you need one special crafted STRING reformat as another STRING , then you do both. First convert it to date, as described in 2 , then convert back to string, as described in 1 with needed format.
4. And one more case - if you want to change output format, then you need to ALTER SESSION variable NLS_DATE_FORMAT.

i am do something like this but it seems not DRY and code smell:

SELECT 
   distinct 
   attach_offices.user_id as user_id, 
   attach_offices.ab_id,
   users.name,
   users.role,
   users.is_admin,
   to_date(to_char(to_date('2013-11-05T10:06:21+04:00', 'YYYY-MM-DD"T"HH24:MI:SS"+04:00"'), 'YYYY-MM'),'YYYY-MM') as month_m         
FROM attach_offices 
LEFT JOIN users ON users.id = user_id
WHERE attach_offices.ab_id = 999999999 and
to_date(to_char(to_date('2013-11-05T10:06:21+04:00', 'YYYY-MM-DD"T"HH24:MI:SS"+04:00"'), 'YYYY-MM'),'YYYY-MM') between to_date(to_char(dt_begin, 'YYYY-MM'), 'YYYY-MM') and to_date(to_char(dt_end, 'YYYY-MM'), 'YYYY-MM')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM