1

I would like to know how to use Moment.JS to caluculate the number of hours on a given day. The reason is that a regular day will be 24 hrs. But the day that daylight savings time starts in the Spring will be 25hrs.

OR how can I use moment.js or even js to calculate if daylight savings date in the spring has been reached bearing in mind that DST starts after 2a.m.

The code I am trying to use is

moment([2017, 2, 12]).isDST();

However how can i used it such that not only does it tell me if its DST but also can check if its after 2 a.m.

Jacklyn N
  • 77
  • 1
  • 12
  • http://stackoverflow.com/questions/11887934/how-to-check-if-the-dst-daylight-saving-time-is-in-effect-and-if-it-is-whats – manonthemat Dec 06 '16 at 20:53
  • 1
    and http://stackoverflow.com/questions/21918095/moment-js-how-to-detect-daylight-savings-time-and-add-one-day – manonthemat Dec 06 '16 at 20:53
  • Please read [ask]. Key phrases: "Search, and research" and "Explain ... any difficulties that have prevented you from solving it yourself". – Heretic Monkey Dec 06 '16 at 21:04
  • Honestly, the documentation Moment.js is really good and has plenty of info on available functionality, like the [`isAfter`](http://momentjs.com/docs/#/query/is-after/) function... – Heretic Monkey Dec 06 '16 at 21:35

1 Answers1

4

Simply get the difference in hours between the start of the day, and the start of the next day.

var m = moment([2017, 2, 12]); // your moment object, however you create it.

var a = moment(m).startOf('day');
var b = moment(m).add(1, 'day').startOf('day');

var h = b.diff(a, 'hours'); // 23, 24, 25, etc.

Note that time zones are different all over the world. Some do DST, some don't. Some do it on different dates and different times. It's even possible to get 23.5 or 24.5 as a result, since there is at least one place that has a 30-minute DST bias instead of the normal 1-hour (Lord Howe Island, Australia). And also there are places that have transitions not related to DST, such as when Venezuela moved their standard time from UTC-04:30 back to UTC-04:00 in May 2016.

Also, you said:

... But the day that daylight savings time starts in the Spring will be 25hrs.

It's actually the Fall that has an extra hour. In the Spring, it would be an hour short (23 hours).

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
  • The code above returns 23. It should return 24 as Spring is 25 hrs – Jacklyn N Dec 07 '16 at 19:42
  • No, in the spring it is 23 hours. For the US, the hour from 2:00 through 2:59 is *skipped* as the clock "springs forward", removing an hour from the day. It is 25 hours in the *fall*, when you "fall back" from 1:59 back to 1:00 to repeat the 1:00 hour twice - adding an extra hour to the day. – Matt Johnson-Pint Dec 07 '16 at 23:01