marnusw / date-fns-tz

Complementary library for date-fns v2 adding IANA time zone support
MIT License
1.01k stars 110 forks source link

isDST analogue in date-fns-tz #123

Open CodeSeek-res opened 3 years ago

CodeSeek-res commented 3 years ago

Hi there, I am new with date-fns and migrating on it after momentJS. I have a lot of components that are using

moment.tz(startDate, timezone).isDST();

Is there any analogue in date-fns-tz that could help me with this one?

marnusw commented 3 years ago

Not right now, but I'd be keen to add it. Most of the implementation is based on Luxon. If you're interested in creating a PR for this an approach like https://github.com/moment/luxon/blob/9a7e46b6e635db89c1c94e18a8c53c28341b7c5e/src/datetime.js#L1189 could be used.

spierala commented 1 year ago

Hi,

I created this little isDst fn which is based on the Luxon implementation. Maybe useful as a workaround or it could be used for a future PR.

function isDst(date: Date): boolean {
  // Inspired by https://github.com/moment/luxon/blob/3.0.3/src/datetime.js#L1235-L1244
  // All offsets must be inverted because in Luxon world the offsets are inverted: https://stackoverflow.com/questions/73636558/why-does-luxon-datetime-offset-return-the-opposite-value-of-native-javascript-da

  const offset: number = -date.getTimezoneOffset(); // Invert offset

  const january: Date = new Date(date.getTime());
  january.setMonth(0);
  const januaryOffset = -january.getTimezoneOffset();  // Invert offset

  const may: Date = new Date(date.getTime());
  may.setMonth(4);
  const mayOffset = -may.getTimezoneOffset();  // Invert offset
  return (
    offset > januaryOffset || offset > mayOffset
  );
}