使用moment.js计算出错误的日期差 [英] Wrong date difference calculated using momentjs
问题描述
我正在尝试使用moment js
计算两个日期之间的天数.
I am trying to calculate the number of days between two dates using moment js
.
function (value) {
var expiration= moment(value).format('DDMMYYYY');
var today = moment().format('DDMMYYYY');
var dayToExpiration = moment(expiration- today).format('D[days] ,H[hours]');
console.log(today + " : " + expiration
console.log(dayToExpiration);
结果是:
11102018 : 28102020 //--> 11.10.2018 : 28.10.2018
1 days ,6 hours //why only one day??
推荐答案
简短答案:
正如约翰·马达哈文·里斯(John Madhavan-Reese)在回答中所说,您必须使用时刻持续时间表示两个时刻之间的差异.
Short answer:
As John Madhavan-Reese stated in his answer, you have to use moment Duration to represent the diffecence between two moments in time.
在您的代码中,您将根据expiration
和today
之间的差异创建一个矩对象.此值瞬间解释为自Unix纪元以来的毫秒数(请参见 moment(Number)
),因此您将在1970年1月1日前后的任意一天创建一个矩对象(请参见moment(expiration- today).format()
的输出). format()
中的D
令牌代表月日,因此给出不正确" 输出.
In your code you are creating a moment object from the difference between expiration
and today
. This value is interpreded by moment as the number of milliseconds since the Unix Epoch (see moment(Number)
), so you are creating a moment object for a random day around the 1st January 1970 (see the output of moment(expiration- today).format()
). The D
token in format()
stands for Day of Month, so it gives an "incorrect" output.
您可以使用momentjs' diff()
计算差异,然后创建 moment.duration(Number)
.
You can calculate difference using momentjs' diff()
then you can create a duration using moment.duration(Number)
.
最后,您可以使用 moment-duration-format 插件获得所需的输出在(作者:John Madhavan-Reese:D)
Finally you can get your desired output using moment-duration-format plug-in (by John Madhavan-Reese :D)
这里有一个现场样本:
function getDiff(value) {
var expiration= moment(value); // Parse input as momement object
var today = moment(); // get now value (includes current time)
// Calculate diff, create a duration and format it
var dayToExpiration = moment.duration(Math.abs(today.diff(expiration))).format('D[days], H[hours]');
console.log(today.format('DDMMYYYY') + " : " + expiration.format('DDMMYYYY'));
console.log(dayToExpiration);
}
getDiff('2018-10-28');
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/2.2.2/moment-duration-format.min.js"></script>
这篇关于使用moment.js计算出错误的日期差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!