Get last day of the Week returns date equivalent to one more day

To get the first day of the week of the date 07/10/2020, I used the function startOfWeek of the date-fns library. In this way, it returned 04/10/2020, which is right.

const primeiroDiaSemana = startOfWeek(new Date(2020, 9, 7)); // 04/10/2020 certo

But when passing that same date to function endOfWeek, to get the last day of the week, it is returned to date 11/10/2020 instead of 10/10/2020.

const ultimoDiaSemana = endOfWeek(new Date(2020, 9, 7)); // 11/10/2020 errado

I would like to know why this happens.

Author: hkotsubo, 2020-10-07

1 answers

The problem is not the generated date, but - probably-the way 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 in broswer (in my case, it is Brasilia Time), and see that in this case the result is correct (last day of the week = October 10, 2018). 2020). Except that the schedule also changed, and it was changed to 23: 59: 59 (after all, endOfWeek takes the "last moment of the week", so it does not just change the day).

And that's the "problem". If I only print the date directly with console.log, the result is implementation dependent: some browsers may show the same result as toString, but the node and the snippet from the above site show the date in UTC. Notice in the example above that the date was shown as 2020-10-11T02:59:59.999Z: The " Z" at the end it indicates that it is in UTC, and as 10/10/2020 at 23:59 in Brasilia Time corresponds to 11/10/2020 at 02:59 in UTC, you end up having the impression that the date is "wrong". It is not, it is only the way of visualization - and the timezone used for it-that ended up changing the final result.


This all happens because JavaScript's Date 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 .

 1
Author: hkotsubo, 2020-10-07 16:12:05