Skip to content

Instantly share code, notes, and snippets.

@pratikagashe
Created May 4, 2020 10:07
Show Gist options
  • Save pratikagashe/9d84e6e18a873000444a9a9b969181ee to your computer and use it in GitHub Desktop.
Save pratikagashe/9d84e6e18a873000444a9a9b969181ee to your computer and use it in GitHub Desktop.
Converting the Date into different time zone with DST check
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
}
}
@ooglek
Copy link

ooglek commented Oct 5, 2022

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.

var january = new Date('2022-01-01T00:00:00Z');
var july = new Date('2022-07-01T00:00:00Z');
console.log(january.getTimezoneOffset() + ' vs ' + july.getTimezoneOffset()); // Outputs "-540 vs -540"

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment