2017-08-28 88 views
0

嗯,我只是无法使用moment.js递增日期。我在我的代码中得到一个javascript日期对象,将它包装到moment函数中,计算我需要添加到初始日期的小时数,并且在我使用.add方法后没有任何反应。尝试做像currentTime.add(2, 'hours')这样的工作,这并不奏效。我做错了什么?无法使用moment.js递增日期

const currentTime = moment(ioc.get<Main.IArchiveManager>("ArchiveManager").getCurrentDate()); 
const speed = this.getData().speed; 
const distance = this.calcDistanceFromPrevPoint(initialPoint,prevPoint); 
const timeToReachPoint = (distance/speed) * 60; 
const estimatedTime = currentTime.add(timeToReachPoint, 'hours'); 
debugger; 
return estimatedTime; 

这是从我的devtool的截图,让你知道是怎么回事:enter image description here

+0

是什么让你觉得这是错的? 'currentTime'的原始值是什么? – Barmar

+2

你知道'add()'修改对象的位置,它不会返回一个新的对象,对吧? – Barmar

+0

你必须使用['format()'](http://momentjs.com/docs/#/displaying/format/)来显示矩对象的值。请参阅[这里](https://stackoverflow.com/a/44812821/4131048)了解与控制台中打印值有关的问题。 – VincenzoC

回答

1

你必须使用format()(或.toString().toISOString())来显示时刻对象的值。

需要注意的是:

  • 时刻对象是可变的,因此调用add会改变原来的对象,如果你需要,你可以使用clone()方法
  • 不要使用Internal properties(前缀为_

你的代码很好,你只是记录错误的方式对象:

const currentTime = moment(); 
 
console.log(currentTime.format()) 
 
const speed = 0.1//this.getData().speed; 
 
const distance = 20.56;// this.calcDistanceFromPrevPoint(initialPoint,prevPoint); 
 
const timeToReachPoint = (distance/speed) * 60; 
 
const estimatedTime = currentTime.add(timeToReachPoint, 'hours'); 
 
console.log(estimatedTime.format())
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

2

一切工作正常。您在之后记录了currentTime的值。请记住.add()更改对象的值,它不会返回副本,而是返回对象本身(以获得更好的链接)。看到我的例子,你会看到传入的console.log,被调用两次,但在不同的时间显示你所期望的值。

var time = moment(new Date()); 
 
console.log(time); 
 
time.add(2,'h'); 
 
console.log(time)
<script src="https://momentjs.com/downloads/moment.min.js"></script>

+0

当你突出显示那个时刻对象是可变的,如果我打开控制台,然后运行你的代码片段,我会得到相同的OP输出。正如我在我的回答(和[内部属性](http://momentjs.com/guides/)中所述),请使用'format()','toString()'或'toISOString()'来显示时刻对象的值。 #/ lib-concepts/internal-properties /)guide)。 – VincenzoC

+0

OP的问题不是关于展示,而是更多关于他们认为没有按需要添加的事实。摘录显示了我想强调的行为,增加更多内容不会增加我的观点的清晰度。 – Salketer