0

I am working with some dates in JavaScript that follow the format YYYY-MM-DD HH:MM:SS. When I go to convert this to a date object using const date = new Date(inputDate), I expect to receive a Date object that is in UTC time, however, what I am getting is a date that is in my local timezone.

I have tried following the steps described here to convert to UTC, but I haven't had any success. A workaround I found was to change my input date to include the desired timezone – that is YYYY-MM-DD HH:MM:SS UTC, but this feels like a nasty workaround that does not scale very well.

I also cannot convert the newly created date to UTC after defining it, as this just gives the UTC representation rather than a date using the appropriate timezone

How can I go about having the Date be created in UTC so that any operations done with Date.now() and the created date don't have a timezone difference?

DeveloperRyan
  • 837
  • 2
  • 9
  • 22

2 Answers2

1

Firstly see Why does Date.parse give incorrect results?

If you want a string parsed as UTC, then it either needs to be in a format supported by ECMA-262 such as "YYYY-MM-DDTHH:mm:ss±HH:mm" (where the offset can also be "Z") with an appropriate offset (either +00:00 or Z), or you should parse it yourself. Consider:

// Parse YYYY-MM-DD HH:MM:SS string as UTC
function parseUTC(ts) {
  let [Y, M, D, H, m, s] = ts.split(/\W/);
  return new Date(Date.UTC(Y, M-1, D, H, m, s));
}

// 2021-09-28T15:32:45.000Z
console.log(parseUTC('2021-09-28 15:32:45').toISOString());

You might also do:

let s = '2021-09-28 15:32:45';
new Date(s.replace(' ','T') + 'Z')

However the idea of parsing a string to create another string that is then parsed again by the built–in parser seems inefficient.

RobG
  • 142,382
  • 31
  • 172
  • 209
-2

Good night!

Combining the UTC() and toISOString() methods from Javascript Date Objects can be helpful to you.

  • I believe this still runs into the error I described in my edit, specifically "cannot convert the newly created date to UTC after defining it" since this adjusts the time relative to the new timezone, rather than having the time be defined relative to UTC (e.g. 3:00 PM EST -> 11:00 AM GMT rather than 3:00 PM GMT -> 7:00 EST). – DeveloperRyan Sep 27 '21 at 21:52
  • Maybe [JavaScript's Temporal API](https://tc39.es/proposal-temporal/docs/) can help you. – Ayres Monteiro Sep 27 '21 at 22:27