Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite return wrong week number for 2013?

I have a simple SQL for calculating week number in my reports on SQLite

SELECT STRFTIME('%W', 'date_column')

It was correct for 2009-2012. In 2013 I got always the wrong week number.

For example

SELECT STRFTIME('%W', '2012-02-28')

return '09' and this is correct.

SELECT STRFTIME('%W', '2013-02-28')

return '08' and this is wrong. We have the 9th week.

Is there something in SQLite date time functions that I don't understand? Or is it a bug of SQLite?

like image 239
WebDucer Avatar asked Feb 26 '13 06:02

WebDucer


2 Answers

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."

like image 181
srdan Avatar answered Oct 02 '22 13:10

srdan


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
like image 43
CL. Avatar answered Oct 02 '22 14:10

CL.