7

I need to get the number of seconds from now till today with a specific hour.

moment().diff(moment().hour(23), 'seconds');

The precision is always in hours, I need it to be in seconds.

For example if now is 15:24. I get 28800.

Engineer2021
  • 3,288
  • 6
  • 29
  • 51
Keloo
  • 1,368
  • 1
  • 17
  • 36
  • You might be interested in this [related question](http://stackoverflow.com/questions/21674694/how-can-i-format-time-durations-exactly-using-moment-js) – Denys Séguret Mar 12 '14 at 13:27

2 Answers2

16

moment() is the current time, so if current time is 15:24:32 moment().hour(23) returns 23:24:32. You need to set the minutes and seconds to 0 to get the difference between 15:24:32 and 23:00:00.

This

moment().diff(moment().hour(23).minute(0).second(0), 'seconds');

returns -27328 seconds when the current time is 15:24:32

Preston S
  • 2,751
  • 24
  • 37
0

Piggybacking off of Preston's answer...

If you want to return a positive value then you should put the later moment object first. So in this case moment().hour(23).minute(0).second(0).diff(moment(), 'seconds');

If you're interested in a human readable output, you could also use to or toNow. Here's an example: moment().hour(23).minute(0).second(0).toNow(true); will result in in seconds or in 21 hours

Here's a link to the documentation (which is fantastic):

Brett S
  • 579
  • 4
  • 8