Home > Mobile >  Why in javascript, new Date EPOCH is not in UTC EPOCH?
Why in javascript, new Date EPOCH is not in UTC EPOCH?

Time:06-06

I have trouble with time precision on my backend. here is code sample:

const inputDateString = `2022-05-30 13:45:15` // assume it as UTC without specifying the timezone

// we use loadbalancing and auto-scale so our backend engine might be everywhere,
// so we dont take local time into account, we always treat date as UTC
let systemGetDate = new Date(inputDateString)

console.log(systemGetDate.valueOf()) // => 1653893115000, it should be 1653918315000
// 1653893115000 is GMT: Monday, 30 May 2022 06:45:15, but 2022-05-30 13:45:15 in my local time!
const inputDateStringWithTimezone = `2022-05-30 13:45:15 00`
systemGetDate = new Date(inputDateStringWithTimezone)
console.log(systemGetDate.valueOf()) // => 1653918315000, its right now. but only when timezone explicitly specified

Can we make new Date(string) always treat the input as UTC, without converting it as localtime? I'm fine the Date object is in localtime, but atleast the getTime or valueOf in UTC somehow.

Currently my workaround is by using moment.js library, it can resulting the output what I want.

but I know it will be bad to depends too much on other library, it may break or deprecated later. (https://momentjs.com/docs/#/-project-status, the official itself explain it will be discontinued)

any better workaround to fix this issue? or I should scratch all this, and explicitly specify the timezone all around the system?

CodePudding user response:

const inputDateString = `2022-05-30 13:45:15` // assume it as UTC without specifying the timezone

Timestamps without a timezone or offset are treated as local, not UTC. The format of that particular timestamp is not supported by ECMA-262 so parsing is implementation dependent (see Why does Date.parse give incorrect results?) and may result in an invalid Date or unexpected value.

Can we make new Date(string) always treat the input as UTC, without converting it as localtime?

Yes, by reformatting it to a supported format that the built–in parser should treat as UTC, e.g.:

'2022-05-30T13:45:15Z'

Alternatively you can parse it yourself and pass the values to Date.UTC so they're treated as UTC, e.g.

let date = `2022-05-30 13:45:15`;

// Reformat and use the built–in parser
let reformattedDate = date.replace(' ','T')   'Z';
console.log(new Date(reformattedDate).toISOString());

// Using Date.UTC
let [Y, M, D, H, m, s] = date.split(/\D/);
let d = new Date(Date.UTC(Y, M-1, D, H, m, s));

console.log(d.toISOString());

  • Related