Home > Software design >  How to check Daylight Saving Time with Temporal in Javascript?
How to check Daylight Saving Time with Temporal in Javascript?

Time:09-21

In case I have a Date and I want to check if the time is DST I can use a method, such as the following:

function isDST(d) {
  let jan = new Date(d.getFullYear(), 0, 1).getTimezoneOffset();
  let jul = new Date(d.getFullYear(), 6, 1).getTimezoneOffset();
  return Math.max(jan, jul) != d.getTimezoneOffset();    
}

(source here)

In case I use MomentJS library I reach the same in this way:

moment().isDST();

Anyone knows how to do the same with the upcoming Temporal?

CodePudding user response:

the temporal api has a offsetNanoseconds read-only property

zdt = Temporal.ZonedDateTime.from('2020-11-01T01:30-07:00[America/Los_Angeles]');
zdt.offsetNanoseconds;
  // => -25200000000000

also there's the with method which returns a new object with specified field being overwritten.

i have to admit i haven't tested it but something like this should basically be the equivalent to your function. (month index starts at 1)

function isDST(d) {
  let jan = d.with({month: 1}).offsetNanoseconds ;
  let jul = d.with({month: 7}).offsetNanoseconds ;

  return Math.min(jan, jul) != d.offsetNanoseconds ;    
}

zoned DateTime

refine dev

web dev simplified

  • Related