Home > Blockchain >  Javascript - force new Date constructor to treat argument as UTC
Javascript - force new Date constructor to treat argument as UTC

Time:12-07

Have an API end point that accepts a date and does some processing. I do give via postman the date as UTC (denoted by the Z at the end). Sample input sent from Postman.

{
   "experimentDate":"2022-01-12T12:30:00.677Z", 
}

In the code when I do

let startDate = new Date(experimentDate);
//other calculations e.g get midnight of the startDate
startDate.setHours(0,0,0,0);

The first assignment sets startDate corrected to the current timezone. The rest of my calculations go bad as a result of this. For instance when I use the setHours function setting time to 0, I expect it to be at midnight of the UTC time given but it goes to midnight of my current timezone. Should new Date not keep the date in UTC given that there is a Z at the end of the date?

Should I reconvert it to UTC like below. Is this not redundant?

Date.UTC(startDate.getUTCFullYear(), startDate.getUTCMonth(),
            startDate.getUTCDate(), startDate.getUTCHours(),
            startDate.getUTCMinutes(), startDate.getUTCSeconds())

What is the right way to achieve this?

CodePudding user response:

The Date object will be stored as a UTC date, however there are different methods on it that will set/get the date or time for both UTC and local timezones. Try using .setUTCHours(), rather than .setHours().

CodePudding user response:

You can use the Date constructor to parse the timestamp provided.

Most of the methods will treat the date as a local time. For example, the getHours() method returns the hour for the specified date, according to local time.

However you can use the getUTCXXX() methods to get the UTC date components such as year, month, date, hour etc.

You can also use Date.toISOString() to get the date formatted as UTC.

You can use the Date.UTC method to get UTC midnight, passing in the relevant getUTCFullYear(), getUTCMonth(), getUTCDay() etc. from the experiment date.

This can then be passed to the Date constructor.

let timestamp = "2022-01-12T12:30:00.677Z";

const experimentDate = new Date(timestamp);
const midnightUTC = new Date(Date.UTC(experimentDate.getUTCFullYear(), experimentDate.getUTCMonth(), experimentDate.getUTCDate()))

console.log('Experiment date (UTC): ', experimentDate.toISOString());
console.log('Midnight (UTC):        ', midnightUTC.toISOString());

You can also use Date.setUTCHours() to do the same thing.

let timestamp = "2022-01-12T12:30:00.677Z";

const experimentDate = new Date(timestamp);
const midnightUTC = new Date(experimentDate);
midnightUTC.setUTCHours(0,0,0,0);

console.log('Experiment date (UTC): ', experimentDate.toISOString());
console.log('Midnight (UTC):        ', midnightUTC.toISOString());

  • Related