The problem is not the generated date, but - probably - how you are showing/printing it.
Using your example and showing the dates in 2 different ways, we have:
const primeiroDiaSemana = dateFns.startOfWeek(new Date(2020, 9, 7));
const ultimoDiaSemana = dateFns.endOfWeek(new Date(2020, 9, 7));
console.log(primeiroDiaSemana.toString()); // Sun Oct 04 2020 00:00:00 GMT-0300 (Horário Padrão de Brasília)
console.log(ultimoDiaSemana.toString()); // Sat Oct 10 2020 23:59:59 GMT-0300 (Horário Padrão de Brasília)
// sem toString, imprime em UTC
console.log(primeiroDiaSemana); // 2020-10-04T03:00:00.000Z
console.log(ultimoDiaSemana); // 2020-10-11T02:59:59.999Z
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.min.js"></script>
First I used toString()
, which formats the date according to the Timezone (time zone) that is configured on broswer (in my case, is the Time of Brasilia), and see that in this case the result is correct (last day of the week = October 10, 2020). However, the timetable also changed, and was changed to 23:59:59 (after all, endOfWeek
takes the "last moment of the week", so it doesn’t just change the day).
And that’s the "problem". If I just print the date directly with console.log
, the result is dependent on the implementation: some browsers can display the same result as toString
, but the Node and the snippet from the above site show the date on UTC. Note in the above example that the date was shown as 2020-10-11T02:59:59.999Z
: the "Z" at the end indicates that it is in UTC, and as 10/10/2020 at 23:59 at the Time of Brasilia corresponds to 11/10/2020 at 02:59 in UTC, you end up getting the impression that the date is "wrong". It is not, it is only the form of visualization - and the Timezone used for such - that ended up changing the final result.
This all happens because the Date
Javascript actually represents a timestamp (a point in the timeline), not a specific date (a single value of day, month, year, hour, minute and second).
For more details, read here, here, here, here and here.
Thank you very much, hkotsubo! Very enlightening.
– Raphael