将持续时间添加到某个时刻(moment.js)

Add a duration to a moment (moment.js)

本文关键字:moment js 时刻 持续时间 添加      更新时间:2023-09-26

Moment版本:2.0.0

在阅读了文档后,我认为这将是直接的(Chrome控制台):

var timestring1 = "2013-05-09T00:00:00Z";
var timestring2 = "2013-05-09T02:00:00Z";
var startdate = moment(timestring1);
var expected_enddate = moment(timestring2);
var returned_endate = startdate.add(moment.duration(2, 'hours'));
returned_endate == expected_enddate  // false
returned_endate  // Moment {_i: "2013-05-09T00:00:00Z", _f: "YYYY-MM-DDTHH:mm:ss Z", _l: undefined, _isUTC: false, _a: Array[7]…}

这是一个微不足道的例子,但我甚至无法让它发挥作用。我觉得我错过了一些重要的东西,但我真的不明白。即使这样,这似乎也不起作用:

startdate.add(2, 'hours')
    // Moment {_i: "2013-05-09T00:00:00Z", _f: "YYYY-MM-DDTHH:mm:ss Z", _l: undefined, _isUTC: false, _a: Array[7]…}

任何帮助都将不胜感激。

编辑:我的最终目标是制作一个二进制状态图,就像我在这里所做的那样:http://bl.ocks.org/phobson/5872894

正如您所看到的,在处理这个问题时,我目前正在使用伪x值。

我认为您错过了.add() 文档中的一个关键点

通过添加时间来更改原始时刻。

您似乎将其视为返回不可变结果的函数。容易犯错误。:)

如果使用返回值,则它与您开始使用的对象是相同的实际对象。它只是为了方便方法链接而返回的。

您可以通过克隆时刻来解决此行为,如本文所述。

此外,不能仅使用==进行测试。您可以将每个时刻格式化为相同的输出并进行比较,也可以只使用.isSame()方法。

您的代码现在是:

var timestring1 = "2013-05-09T00:00:00Z";
var timestring2 = "2013-05-09T02:00:00Z";
var startdate = moment(timestring1);
var expected_enddate = moment(timestring2);
var returned_endate = moment(startdate).add(2, 'hours');  // see the cloning?
returned_endate.isSame(expected_enddate)  // true

我正在开发一个跟踪实时路线的应用程序。乘客希望显示驾驶员的当前位置以及到达他/她的位置的预计到达时间。所以我需要在当前时间中添加一些持续时间。

所以我找到了下面提到的方法来做同样的事情。我们可以在当前时间中添加任何持续时间(小时、分钟和秒):

var travelTime = moment().add(642, 'seconds').format('hh:mm A');// it will add 642 seconds in the current time and will give time in 03:35 PM format
var travelTime = moment().add(11, 'minutes').format('hh:mm A');// it will add 11 mins in the current time and will give time in 03:35 PM format; can use m or minutes 
var travelTime = moment().add(2, 'hours').format('hh:mm A');// it will add 2 hours in the current time and will give time in 03:35 PM format

它满足了我的要求。也许它能帮助你。

对于有startTime(如12h:30:30)和duration(如120分钟)的人,你可以这样猜测endTime

const startTime = '12:30:00';
const durationInMinutes = '120';
const endTime = moment(startTime, 'HH:mm:ss').add(durationInMinutes, 'minutes').format('HH:mm');
// endTime is equal to "14:30"