Rusurano
Rusurano

Reputation: 552

dayjs().startOf('day') shifts two hours back

I'd like to sort out a dayjs problem I am experiencing. Right now, I'm out of clues and/or guesses of what can happen, apart from the bad timezone setting. But again, how could timezone play a role here, if I didn't even modify it anywhere in my code?

I'm having a dayjs object, and I want to get the beginning of the day with it. When printing the output into console, I get:

d {
  '$L': 'en',
  '$d': 2021-03-18T22:00:00.000Z,
  '$x': {},
  '$y': 2021,
  '$M': 2,
  '$D': 19,
  '$W': 5,
  '$H': 0,
  '$m': 0,
  '$s': 0,
  '$ms': 0
}

Efficiently that means that month, day, week, hour, minute, second, and millisecond options are set correctly (they are all zero), but the date field in $d is absolutely wrong (it's shifted 2 hours back for some reason). How do I make the date update correctly as well? Please explain why does it happen so I will know how to deal with it in the future.

Using node.js with express.js to run day.js on. Node version is 15.8.0 Express version is 4.17.1 Dayjs version is 1.10.4

Many thanks in advance!

Upvotes: 11

Views: 18033

Answers (2)

Milind Phalke
Milind Phalke

Reputation: 1

The version of dayjs - 1.10.4 seems to have an issue with the startof the date. As it generally shifts the startDate by 2-5 hours.

So it's better to use moment() in place of dayjs(). I used the moment() - v2.29.1 and the issue was resolved.

instead of - let dateValue = dayjs(startDate)

use

let dateValue = moment(startDate)

Upvotes: -5

fanny_pc
fanny_pc

Reputation: 196

(Sorry for the redaction, English is not my first language) I can answer with something that I did for my job, meanwhile some other person answer with maybe a better explanation.

In dayjs documentation there's a section for the UTC plugin there's a function called .utcOffset() which can be used to set the offset to the hours to 0, I used it because I had the same issue as you with 5 hours gap, so to obtain the date with hours in 0 I used it like this:

let today = dayjs().utcOffset(0).startOf('date').toDate();

and It gives me the date with hours, minutes and seconds in zero 2021-06-15T00:00:00.000Z

I hope it can be of help to someone.

Upvotes: 18

Related Questions