无法使用moment.js增加日期 [英] Failing to increment date with moment.js

查看:488
本文介绍了无法使用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() )以显示矩对象的值.

请注意:

  • 瞬间对象是可变的,因此调用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>

这篇关于无法使用moment.js增加日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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