Search code examples
javascriptmomentjsdstdays

How to use Momentjs to calculate number of hours on Day light savings Day


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.


Solution

  • 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).