How do you check according to a timezone if you should modify the UTC time to -1 or 1 in Javascript? Need a function that takes in a timezone as string, and a time in UTC format and either add -1 or 1 depending on whether according to the timezone there's daylight savings or not and modify the UTC time appropriately. Is there a library that does this?
CodePudding user response:
How do you check according to a timezone if you should modify the UTC time to -1 or 1 in Javascript?
For common offsets, the sign of the offset tells you whether to add or subtract from UTC to get local. So GMT 5:30 means add 5 hours and 30 minutes to UTC to get local.
POSIX offsets (such as those generated by ECMAScript's Date.prototype.getOffset) are the opposite, i.e. they indicate the time to add or subtract from local to get UTC, so in the above case the offset would be -5:30.
Need a function that takes in a timezone as string, and a time in UTC format and either add -1 or 1 depending on whether according to the timezone there's daylight savings or not and modify the UTC time appropriately.
Not all daylight saving offsets are 1 hour, some are 30 minutes. Typically places have a timezone name ending in "standard time" to indicate the normal offset, and a "daylight saving time" or "summer time" for when the daylight saving offset applies.
Offsets also depend on the date, so you need to provide a date and time like "2022-08-31T08:30:00Z".
Is there a library that does this?
Yes, there are many however library recommendations are off topic here. Research them, have a play, pick one you like. Then ask questions about a specific issue and library if you have any.
But you can also use POJS with either Date.prototype.toLocaleString or Intl.DatetimeFormat with suitable options and parsing the resulting string. You might also use Intl.DateTimeFormat.prototype.formatToParts:
let date = '2022-08-31T08:30:00Z';
let loc = 'Asia/Kolkata';
console.log(new Date(date).toLocaleString('en',{
hour: 'numeric',
hour12: false,
timeZone: loc,
timeZoneName: 'short'
}));
console.log(
new Date('2022-08-31T12:00:00Z').toLocaleString('en',{hour:'numeric', hour12:false, timeZone:'Asia/Kolkata', timeZoneName:'short'})
);
Note that the Intl.DateTimeFormat has numerous options for timeZoneName such as shortOffset that aren't widely supported yet so use with caution and stick with older options for wider compatibility.