无法使用moment.js增加日期 [英] Failing to increment date with moment.js
问题描述
好吧,我只是无法使用moment.js增加日期.我在代码中获得了一个javascript日期对象,将其包装到moment
函数中,计算需要添加到初始日期的小时数,并且在使用.add
方法后没有任何反应.尝试做类似currentTime.add(2, 'hours')
的操作,但效果也不佳.我在做什么错?
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的屏幕截图,所以您知道发生了什么:
您必须使用 format()
(或 .toString()
或 .toISOString()
)以显示矩对象的值.>
请注意:
您的代码很好,您只是以错误的方式记录了瞬间对象:
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>
Well, I just can't increment a date with moment.js. I get a javascript date object in my code, wrap it into moment
function, calculate the amount of hours I need to add to the initial date and after I use .add
method nothing happens. Tried doing something like currentTime.add(2, 'hours')
, that didn't work as well. What am I doing incorrectly?
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;
this is a screenshot from my devtool so you know what is going on:
You have to use format()
(or .toString()
or .toISOString()
) to display the value of a moment object.
Note that:
- moment objects are mutable, so calling
add
will change the original object, if you need you can use theclone()
method - Do not use Internal properties (prefixed with
_
)
Your code is fine, you are just logging moment object the wrong way:
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>
这篇关于无法使用moment.js增加日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!