Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minutes since midnight in Momentjs

In pure JS, this would be how.

How can I find out the number of minutes since midnight for a given moment object (without extracting to Date)?

  • Must take into account DSTs
  • Minutes should be rounded
  • Must work with local time (not convert to UTC)
like image 406
bguiz Avatar asked Aug 05 '14 01:08

bguiz


People also ask

Should you still use MomentJS?

Moment. js is a fantastic time & date library with lots of great features and utilities. However, if you are working on a performance sensitive web application, it might cause a huge performance overhead because of its complex APIs and large bundle size.

Is MomentJS deprecated?

Moment construction falls back to js Date. This is discouraged and will be removed in an upcoming major release. This deprecation warning is thrown when no known format is found for a date passed into the string constructor.

How do I get current year in MomentJS?

Calling format('YYYY') will invoke moment's string formatting functions, which will parse the format string supplied, and build a new string containing the appropriate data. Since you only are passing YYYY , then the result will be a string containing the year. If all you need is the year, then use the year() function.


2 Answers

// Your moment var mmt = moment();  // Your moment at midnight var mmtMidnight = mmt.clone().startOf('day');  // Difference in minutes var diffMinutes = mmt.diff(mmtMidnight, 'minutes'); 

By default, moment#diff will return number rounded down. If you want the floating point number, pass true as the third argument. Before 2.0.0, moment#diff returned rounded number, not a rounded down number.

Consider this pseudocode because I haven't test to see if the difference takes into account DST.

like image 178
Tuan Avatar answered Sep 25 '22 20:09

Tuan


This is what I have at the moment:

    if (!moment.isMoment(mmt)) {         return 0;     }     var hh = mmt.get('hour');     var mm = mmt.get('minute');     return hh*60 + mm; 

I am not sure if it takes into account various edge cases; comment if this is the case, or provide an alternate answer.

like image 45
bguiz Avatar answered Sep 26 '22 20:09

bguiz