当仅剩零小时时,Moment JS Subtract 方法返回 12 小时差 [英] Moment JS Subtract method returns 12 hour difference when there is only zero hour left

查看:123
本文介绍了当仅剩零小时时,Moment JS Subtract 方法返回 12 小时差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 时刻js.我正在使用以下代码,

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();

它工作正常,直到剩余小时数大于零.例如,当时间到达 12:10 PM 时,它应该显示剩余 0 小时 40 分钟,而不是显示剩余 12 小时 40 分钟.

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.

如何解决这个问题?

推荐答案

你不能使用 toLocaleTimeString() 因为它显示日期的时间,所以,正如 Trunst 在他的评论中所说,如果是 12 小时格式,它将显示 12 而不是 0.

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.

您可以使用 format() 函数momentjs 强制其为 24 小时格式:

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

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

查看 演示,其中显示了您的 ETA 倒计时

Check a demo there which displays a countdown to your ETA

注意使用 diff 而不是 substract,请参阅 Matt Johnson 的注释以获取解释.

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

请注意,如果您想显示超过 24 小时的预计到达时间,则必须使用 duration 对象momentjs.

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

这篇关于当仅剩零小时时,Moment JS Subtract 方法返回 12 小时差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆