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?
CodePudding user response:
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.
CodePudding user response:
Good night!
Combining the UTC() and toISOString() methods from Javascript Date Objects can be helpful to you.