Home > front end >  Timezone is getting change by 1 hour in EST timeZone for month value greater than 1
Timezone is getting change by 1 hour in EST timeZone for month value greater than 1

Time:02-18

I am working on one of my client issue. I have changed my system timezone to "(UTC-5:00) Eastern time (US & canada)". I wrote below code in my project -

new Date(year,month.date)

I observed that if month value is 0 or 1 ,then it is working fine -

new Date(2021,1,21)
Sun Feb 21 2021 00:00:00 GMT-0500 (Eastern Standard Time)

but if month value is greater than 1, then timezone is getting change by 1 hour-

new Date(2021,2,21)
Sun Mar 21 2021 00:00:00 GMT-0400 (Eastern Daylight Time)

which is causing problem. please someone suggest on this that why it is happening and what might be solution of this. expected answer should be in javascript or angular. moment library also will be accepted. this issue is only reproducible for few timezone. It is working fine for IST.

CodePudding user response:

your date is ticking over the EST's daylight savings time

You can get round this by specifying the timezone of your date, for example:

new Date(2021, 3, 21).toLocaleString("en-US");

will return the date formatted to en-US timezone, or you can use something like the Date.UTC function to ensure all your dates are handled as a UTC timezone

datetimes are a bit of a nightmare in JS - these might not fix your issue, but hopefully they'll point you in the right direction.

In regards to packages, if you're doing a lot of datetime work i would suggest Moment or the smaller Luxon packages, they really take a lot of the headache out of JS dates

CodePudding user response:

EMCAScript uses the host system settings for timezone offset. The output ofDate.prototype.toString is based on those settings and inferred rules for standard and daylight saving if observed.

Given one timestamp says Eastern Standard Time and the other Eastern Daylight Time, it shows that the dates relate to times when the offset rules based on your system's regional settings change from standard time to daylight saving time.

If you only want standard time, there should be an option in your regional settings to turn off observing daylight saving. But that will be a system wide setting and will potentially affect the displayed dates and times everywhere on your system.

Alternatively, you can use toLocaleString with a location that is in the US EST timezone but doesn't observe daylight saving, e.g. America/Panama. However, the format is different to that of the default toString. If you want the same format, you'll have to construct it yourself, see How to format a JavaScript date

console.log(new Date(2022,1,25).toLocaleString('en',{timeZone:'America/Panama', timeZoneName:'short'}));

Note that this has no effect on the Date instance itself, it only changes the values displayed when toLocaleString is called this way.

  • Related