547n00n
547n00n

Reputation: 1536

offset time zone problem with toIsoString : does not convert well the date object

I'm trying to set a date that take the begin of year 2020 with javascript and convert it to isoString; the problem is that always I got a date like this : like "2019-12-31T23:00:00.000Z" !!

  start: Date =  new Date(new Date().getFullYear(), 0, 1);

how to set the date with this format : "2020-01-01T23:00:01.000Z"

Upvotes: 0

Views: 569

Answers (1)

RobG
RobG

Reputation: 147363

The date produced by new Date() makes an allowance for the host timezone offset, the toISOString method is UTC so unless the host is set to UTC, there will be a difference equal to the host timezone offset. In the OP that's +01:00.

If you want the start of the year UTC, then you have to first generate a time value as UTC, then use that for the date:

// Get the current UTC year
let year = new Date().getUTCFullYear();
// Create a Date avoiding the local offset
let d = new Date(Date.UTC(year, 0, 1));
// Get a UTC timestamp
console.log(d.toISOString());

If, on the otherhand, you want an ISO 8601 timestamp with the local offset rather than UTC, something like 2020-01-01T00:00:00.000+02:00, you'll have to do that yourself or use a library (per this, thanks to Matt JP), see How to format a JavaScript date.

Upvotes: 1

Related Questions