.add()
moment.js
的方法
Mutates the original moment by adding time.
var now = moment([2015, 11, 29, 14]);
var tomorrow = now.add(1, 'd');
// now has changed
如果我有一个固定的“现在”时刻,我想稍后在我的程序中重复使用,那么正确的方法是什么?
我发现的最好的结构是这样的
var ref = [2015, 11, 29, 14];
var now = moment(ref);
var tomorrow = moment(ref).add(1, 'd');
var start = moment(ref).startOf('day'); // beginning of today
var end = moment(ref).add(1, 'd').endOf('day'); // end of tomorrow
但对我来说它看起来很笨拙。
最佳答案
Note: It should be noted that moments are mutable. Calling any of the manipulation methods will change the original moment.
If you want to create a copy and manipulate it, you should use moment#clone before manipulating the moment. More info on cloning.
var now = moment([2015, 11, 29, 14]);
var tomorrow = now.clone().add(1, 'd');
var start = now.clone().startOf('day'); // beginning of today
var end = now.clone().add(1, 'd').endOf('day'); // end of tomorrow
一个quick look at their code on Github显示他们所做的只是return new Moment(this)
,因此您可以通过执行new Moment(now)
而不是now.clone来完成同样的事情()
如果您更清楚的话。我个人认为您应该使用您认为最清楚的任何方法。
关于javascript - 如何处理固定日期的突变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34520370/