添加持续时间到片刻(moment.js) [英] Add a duration to a moment (moment.js)

查看:654
本文介绍了添加持续时间到片刻(moment.js)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

时刻版本:2.0.0

Moment version: 2.0.0

阅读完docs ,我认为这很简单(Chrome控制台):

After reading the docs, I thought this would be straight-forward (Chrome console):

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]…}

这是一个简单的例子,但我甚至无法让它发挥作用。我觉得我在这里错过了一些大事,但我真的不明白。即便如此,这似乎也不起作用:

This is a trivial example, but I can't even get it to work. I feel like I'm missing something big here, but I really don't get it. Even this this doesn't seem to work:

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]…}

我们非常感谢任何帮助。

Any help would be much appreciated.

编辑:
我的最终目标是创建一个二元状态图表,就像我在这里工作的那样:
http://bl.ocks.org/phobson/5872894

如你所见,我目前正在使用虚拟x-我在解决这个问题时的价值。

As you can see, I'm currently using dummy x-values while I work through this issue.

推荐答案

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


通过增加时间来改变原始时刻。

Mutates the original moment by adding time.

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

You appear to be treating it as a function that returns the immutable result. Easy mistake to make. :)

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

If you use the return value, it is the same actual object as the one you started with. It's just returned as a convenience for method chaining.

你可以通过克隆时刻来解决这个问题,如此处所述

You can work around this behavior by cloning the moment, as described here.

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

Also, you cannot just use == to test. You could format each moment to the same output and compare those, or you could just use the .isSame() method.

您的代码现在是:

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

这篇关于添加持续时间到片刻(moment.js)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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