SQLite return wrong week number for 2013?

醉酒当歌 提交于 2019-12-05 05:39:52

CL's answer works fine for OP's definition of "right", which is not quite the same as ISO definition. ISO week numbers are always in the range 1-53 (no week 0), and the last 3 days of a year may fall into Week 1 of the following year, just like the first 3 days may fall into Week 52 or 53 of the preceding year. To take these corner cases into account, you need to do something like:

SELECT
    (strftime('%j', date(MyDate, '-3 days', 'weekday 4')) - 1) / 7 + 1 AS ISOWeekNumber
FROM MyTable;

As a side note, SQLite's Date and Time documentation does link to the POSIX strftime man page, which defines %W modifier as: "week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0."

To convert from SQLite's undocumented week definition (first week is the week with the year's first Monday in it, or the week with 7 January in it) to the ISO week definition (first week is the week with the year's first Tuesday in it, or the week with 4 January in it), we let SQLite compute the week of the year's 4 January. If that is not one, we have to increase the week number:

SELECT strftime('%W', MyDate)
       + (1 - strftime('%W', strftime('%Y', MyDate) || '-01-04'))
FROM MyTable
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!