Home > Blockchain >  Is there a way to modify date iso string such that in JS, new Date(isoString) does not return date i
Is there a way to modify date iso string such that in JS, new Date(isoString) does not return date i

Time:01-04

After setting system clock to EST, on converting iso string to date object using Date constructor we noticed that dates between March and November return offset time -4 hrs i.e. daylight saving time and otherwise offset is -5hrs.

For eg, in below screenshot ISO date string is of September month (i.e between March & November) & date returned from new Date() is having offset of -4 (underlined) enter image description here

And for January month , returned date is having offset of -5 (underlined) enter image description here

So on calculating the difference in days between the above 2 dates gives the difference in decimal, where the expectation for the difference is that it should be an integer value.

I am calculating the difference using (a.getTime() - b.getTime())/(24*3600000).

Is there a way to modify date iso string such that in javascript, new Date(isoString) does not return date in daylight saving time ?

The automatic change of offset from -5 to -4 & vice versa is causing problems in calculating difference in days in integer and also on adding number of days to a date.

Or is there a better way to handle these issues by an alternate approach? If this can be handled using moment, I'm fine with it.

CodePudding user response:

Please post text, not images.

The strings in the OP are in a format supported by the built–in parser, so should be parsed correctly by modern browsers. As they don't have an offset, they're parsed as local. That results in a time value that is an offset from 1970-01-01T00:00:00Z and is used for the new Date instance.

If the host system is set for a place or region that observes daylight saving at the dates and times represented by the timestamp, it will be used to calculate the time value. If one is during a period of DST and one isn't, then the time difference between them will not be an integer multiple of 24 hours (or 8.64e7 milliseconds).

If you want every day to be 24 hours long, use UTC for everything (including the strings you're parsing). One way is using date–only ISO 8601 strings, such as 2024-09-29. e.g.

let days = (new Date('2024-09-29') - new Date('2023-01-02')) / 8.64e7;

console.log(days); // 636

// or
console.log((Date.UTC(2024,8,29) - Date.UTC(2023,0,2)) / 8.64e7)

  • Related