1

I want to display remaining hours, minutes and seconds to a specific preset time (01:00 PM) from the current time with help of moment js. I am using the following code,

var n = new Date();
var end = new Date(n.getFullYear(), n.getMonth(), n.getDate(), 13, 0, 0, 0);
var a = moment(end);
var b = moment(n);
var eta = a.subtract(b).toDate().toLocaleTimeString();

It works fine until the remaining hours is greater than zero. For example whenever the time reaches 12:10 PM it should display 0 Hours and 40 Minutes remaining, instead show 12 hours and 40 minutes remaining.

How to get this fixed?

  • The problem seems to me to be `toLocaleTimeString()` which formats the time to 12-hour conventions and in 12-hour conventions 0 is interpreted as 12 AM. – Trunst Nov 30 '15 at 12:22

1 Answers1

1

You can't use toLocaleTimeString() because it displays the time of a date, so, as Trunst said in his comment, it will display 12 instead of 0 in case of a 12-hour format.

You can use the format() function of momentjs to force it to 24-hours format:

var eta = a.subtract(b).format("H:mm:ss");

Check a demo there which displays a countdown to your ETA

Note the use of diff instead of substract, see Matt Johnson's comment for the explanations.


Note that if you wan to display an ETA greater than 24h, you will have to use the duration object of momentjs.

Finrod
  • 2,425
  • 4
  • 28
  • 38
  • Sorry, but this isn't a good approach. `subtract` is for removing some amount of elapsed time from a moment object to get an earlier moment object. The correct function to get the difference between two moments is `diff`. See the question I marked as duplicate and the accepted answer for how to format the output. – Matt Johnson-Pint Nov 30 '15 at 17:39
  • thanks to all for the valuable informations – Deepak Jose Dec 01 '15 at 03:51
  • Thanks @MattJohnson, I edited my example to reflect your comment. – Finrod Dec 01 '15 at 08:25