且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

无法使用moment.js增加日期

更新时间:2023-01-31 14:40:55

您必须使用 format() (或 .toString() .toISOString() )以显示矩对象的值.>

请注意:

  • 瞬间对象是可变的,因此调用add会更改原始对象,如果需要,可以使用 clone() 方法
  • 请勿使用内部属性(以)

您的代码很好,您只是以错误的方式记录了瞬间对象:

 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 the clone() 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>