Moment JS Subtract method returns 12 hour difference when there is only zero hour left [duplicate]

牧云@^-^@ 提交于 2020-03-24 09:45:27

问题


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?


回答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.



来源:https://stackoverflow.com/questions/33998399/moment-js-subtract-method-returns-12-hour-difference-when-there-is-only-zero-hou

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!