I have been using the following statement to get the week of the year from a date:
TO_CHAR(TO_DATE(tbl.col,'YYYY/MM/DD'),'IW') AS week
Now I'm receiving strange results and I can't seem to figure this out. For the following dates I receive the week 24:
19-Jun-17 || 23-Jun-17 || 24-Jun-17 || 25-Jun-17 || 29-Jun-17 || 30-Jun-17
For these, I receive 25:
20-Jun-17 || 21-Jun-17 || 22-Jun-17 || 26-Jun-17 || 27-Jun-17 || 28-Jun-17
...and this continues. I'm a bit worried now that all my queries show incorrect data. The only reason I have noticed it only now is because there are no results for weeks 26, 27, 30, 31 and 32 which is not the case in any of my other queries.
Any suggestions or pointers towards possible errors are appreciated.
Thank you!
[TL;DR] Just use: TO_CHAR( tbl.col, 'IW' )
You have multiple issues:
The datatype is "date"
You are calling TO_DATE( string, format_model )
with a DATE
(not a VARCHAR2
) which causes Oracle to do an implicit conversion of the DATE
to a VARCHAR2
using the NLS_DATE_FORMAT
session parameter as the format model just so you can convert it back to a DATE
. So, you are effectively doing:
TO_CHAR( TO_DATE( TO_CHAR( tbl.col, ( SELECT VALUE FROM NLS_SESSION_PARAMETERS WHERE PARAMETER = 'NLS_DATE_FORMAT' ) ), 'YYYY/MM/DD' ), 'IW' )
Do not do this , just use:
TO_CHAR( tbl.col, 'IW' )
If you do that then the following issues are irrelevant.
You are using YYYY
for the year format model so all the years are going to be in the 1st Century AD.
Example :
SELECT TO_CHAR( TO_DATE( '19-Jun-17', 'YYYY/MM/DD' ), 'YYYY-MM-DD' ) AS dt FROM DUAL
Output :
DT ---------- 0019-06-17
If you aren't going to fix the implicit string conversion then you would probably want either:
TO_CHAR(TO_DATE(tbl.col,'DD-MON-YY'),'IW') AS week
or (depending on whether you want the year 99 to be 1999 or 2099):
TO_CHAR(TO_DATE(tbl.col,'DD-MON-RR'),'IW') AS week
You are using the MM
format model for MON
formatted data - this is not necessarily an issue as MM
also matches MON
and MONTH
but you should probably use the correct model.
You have the wrong order of year and day. those weeks are correct for example 17.06.2020 is week 25, 17.06.2023 is week 24 and so on.
Try: TO_CHAR(TO_DATE(tbl.col,'DD-MON-YY'),'IW') AS week
or something
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.