0

I am sending a selected date set to the start of the day ( hours, minutes and seconds set to 0) converted to UTC date and the offset from new Date().getTimezoneOffset() from my client side application to my server. In the server I need to convert the UTC date back to the original date to show in a report. But when I try to convert the UTC date back to the date in the original timezone, it is off by a date. I have found that this is the case for dates for dates before November 4th and believe it might be because of daylight savings time.

I am using moment on the server with moment(utcDate).utcOffset(offset).format('DD/MM/YYYY') to try and get the correct date.

If the date being sent is the UTC formatted date of 26/10/2019 00:00 from PST then at the server when it is converted back, I am getting 25/10/2019.

The UTC date being sent from the client is 2019-11-01T07:00:00.000Z and offset being sent is 480. At the server I tried to get the date back by using moment('2019-11-01T07:00:00.000Z').utcOffset(-480).format('DD/MM/YYYY hh:mm a') and got "31/10/2019 11:00 pm"

curious
  • 11
  • 1

1 Answers1

1

If the client is in the Pacific time zone, 480 (UTC-8) is the incorrect offset for November 1st 2019. On that day, DST was in effect and the offset was UTC-7.

The problem is not with your interpretation on the server side, but rather how you are collecting the time zone offset on the client side.

new Date().getTimezoneOffset()

This gives the offset in effect for the date object given. new Date() gives the current date and time. DST for 2019 ended at 2 am on November 3rd, thus you will get a different offset when you run it now than was in effect for the previous date in question.

You should change your client-side code to return the correct offset:

new Date("2019-11-01T07:00:00.000Z").getTimezoneOffset()  // 420

(Use the existing Date object if you have one already.)

Alternatively, you can change your client-side code to return an ISO string that is in terms of local time and offset, rather than UTC. There are examples of this that just use the Date object here, or you could just use moment().format().

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
  • In addition to this, if the ISO string is sent to the server, then the server will need to deal with parsing and splitting it into UTC and the timezone offset (since the database will likely convert it to UTC and then discard the timezone information). That computation might as well be made by the client then. Just make sure to not store the ISO string into the database only because you also want to store the timezone information. The offset in seconds (not in minutes, since you will usually perform more computations with seconds, due to the Unix timestamp) is then better stored. – Daniel F Nov 12 '19 at 23:09