Search code examples
javascriptdatedate-fns

Discrepancy between date-fns startOfWeek and format W


I'm having a problem with date-fns and the way it handles "start of weeks".

The "start of week" of 2015-01-01, according to my calendar, was 2014-12-29.

But, date-fns#startOfWeek tells me otherwise:

❯❯❯ dateFns.startOfWeek(new Date('2015-01-01'))
Sun Dec 28 2014 00:00:00 GMT+0100 (Central European Standard Time)

If I format the result of startOfWeek (2014-12-28) to just return the week number, what I get is "52" (which doesn't match with the result provided by dateFns#startOfWeek):

❯❯❯ dateFns.format(new Date('2014-12-28'), 'W')
"52"

But, if I format the original date (2015-01-01), it will return "1":

❯❯❯ dateFns.format(new Date('2015-01-01'), 'W')
"1"

Why is there this discrepancy? What's the proper way to get the right "start of week" date and week number?

Note, I'm setting TZ=Etc/UTC in my environment variables when I run the above commands on my Node.js CLI. So it shouldn't be a timezone issue.


Solution

  • What you are getting is correct. By default, a week starts on Sunday. But if you want to start it from Monday, you can do it like this:

    var result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0), {weekStartsOn: 1})

    Reference

    Example:

    var result = dateFns.startOfWeek(new Date('2015-01-01'))
    console.log(result);
    
    result = dateFns.startOfWeek(new Date('2015-01-01'), {weekStartsOn: 1})
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.min.js"></script>

    Concerning the week numbers, W in format() gives you ISO week number, meaning it starts form Monday. Moreover there were only 52 weeks in 2014.

    Source: https://www.epochconverter.com/weeks/2014