0

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"

sahnoun
  • 944
  • 2
  • 22
  • 39
  • `Date = new Date(new Date().getFullYear(), 0, 2, 0, 0, 1);` will produce (for your timezone) exactly what you expect – Jaromanda X May 03 '20 at 00:16
  • `new Date(Date.parse(\`${new Date().getFullYear()}-01-01T23:00:01.000Z\`))` will produce what you want – Jaromanda X May 03 '20 at 00:26
  • @sahnoun - Your code does not create a `string` at all. It creates `Date` object. You may be *seeing* a string representation of that object, but that's not what you are creating here. Also, the two strings you gave are in the same *format* already. They are two different points in time, of course. (`Z` means UTC in ISO 8601 format) . I could see why you might want `"2020-01-01T00:00:00.000"`, but not sure why you'd want `23:00:01.000Z` - a different time entirely (especially with that 1 second). – Matt Johnson-Pint May 03 '20 at 00:30
  • 1
    I *think* what you're looking for is [this](https://stackoverflow.com/a/17415677/634824), perhaps without the offset? – Matt Johnson-Pint May 03 '20 at 00:31

1 Answers1

1

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.

RobG
  • 124,520
  • 28
  • 153
  • 188