Created
May 4, 2020 10:07
-
-
Save pratikagashe/9d84e6e18a873000444a9a9b969181ee to your computer and use it in GitHub Desktop.
Converting the Date into different time zone with DST check
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const d = new Date() | |
// convert to msec since Jan 1 1970 | |
const localTime = d.getTime() | |
// obtain local UTC offset and convert to msec | |
const localOffset = d.getTimezoneOffset() * 60 * 1000 | |
// obtain UTC time in msec | |
const utcTime = localTime + localOffset | |
// obtain and add destination's UTC time offset | |
const estOffset = getEstOffset() | |
const usa = utcTime + (60 * 60 * 1000 * estOffset) | |
// convert msec value to date string | |
const nd = new Date(usa) | |
// Get time zone offset for NY, USA | |
const getEstOffset = () => { | |
const stdTimezoneOffset = () => { | |
var jan = new Date(0, 1) | |
var jul = new Date(6, 1) | |
return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset()) | |
} | |
var today = new Date() | |
const isDstObserved = (today: Date) => { | |
return today.getTimezoneOffset() < stdTimezoneOffset() | |
} | |
if (isDstObserved(today)) { | |
return -4 | |
} else { | |
return -5 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This assumes that the browser that is executing this code is in the US, and assumes that you only want to know whether or not DST is in effect TODAY and not another day.
A person in Japan or any of the non-Daylight Saving Time countries would experience this code differently. Their browser would return the same
getTimezoneOffset()
for both January and July as they do not experience DST.This code ONLY works when the client browser is in the USA AND in a Time Zone that follows Daylight Saving Time, which these places in the US do not: Hawaii, Puerto Rico, most of Arizona, US Virgin Islands, and some others.
With Javascript it does not seem possible to determine Daylight Saving Time using
getTimezoneOffset()
if the browser is outside of a US timezone that follows DST.