Bill
Bill

Reputation: 129

Does DateTimeFormat account for daylight savings time?

I'm converting some time checks that relied on moment-timezone to using INTL.DateTimeFormat.

For context, the code takes a user's current time in ms (Date.now()), and checks it against three time zones (each website has it's own locale):

const formatter = Intl.DateTimeFormat([], {
  timeZone: timezone,
  year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', 
  minute: 'numeric', second: 'numeric',
})

Where timezone is either America/New_York, Europe/London or Europe/Madrid. Formatter is passed into Date.parse to get it into the appropriate ms format.

I'm having some trouble finding out if the function already accounts for daylight savings time. If not, I can do some logic elsewhere to convert the two times I'll be comparing to the appropriate DST value.

Is this something that exists already? Is it under the hood, or part of the first arg for the function? Just having trouble locating the info in the docs.

Upvotes: 4

Views: 1379

Answers (1)

I_Al-thamary
I_Al-thamary

Reputation: 3993

Try this:

<html>
<head>
<script language="JavaScript">

// function to calculate local time
// in a different city
// given the city's UTC offset
function calcTime(city, offset) {

    // create Date object for current location
    d = new Date();
    
    // convert to msec
    // add local time zone offset 
    // get UTC time in msec
    utc = d.getTime() + (d.getTimezoneOffset() * 60000);
    
    // create new Date object for different city
    // using supplied offset
    nd = new Date(utc + (3600000*offset));
    
    // return time as a string
    return "The local time in " + city + " is " + nd.toLocaleString();

}

alert(calcTime('New York ', '-4'));

alert(calcTime('Madrid', '+1'));

alert(calcTime('London', '+1'));

</script>
</head>
<body>

</body>
</html>

Upvotes: 1

Related Questions