Moment.js - 两天的天数差异 [英] Moment.js - two dates difference in number of days
问题描述
我在尝试查找两个日期之间的数字差异时得到的结果不正确:
I get incorrect results when trying to find numeric difference between two dates:
var startDate = moment( $('[name="date-start"]').val(), "DD.MM.YYYY"), // $('[name="date-start"]').val() === "13.04.2016"
endDate = moment( $('[name="date-end"]' ).val(), "DD.MM.YYYY"); // $('[name="date-end"]').val() === "28.04.2016"
var diff = startDate.diff(endDate);
console.log( moment(diff).format('E') );
13.04.2016
和<$ c之间$ c> 28.04.2016 我不应该 3 或 2 天......
Between 13.04.2016
and 28.04.2016
I shouldn't get that difference is 3 or 2 days...
我尝试了多种组合:
- swap
startDate.diff(endDate)
endDate.diff(startDate)
-
format('E')
有一些东西我上来搜索SO
- swap
startDate.diff(endDate)
withendDate.diff(startDate)
format('E')
with something I've come up searching the SO
结果:我总是得到那个差异是3天或2天。
result: all the time I get that difference is 3 or 2 days.
我做错了什么?在此先感谢。
What am I doing wrong? Thanks in advance.
推荐答案
从时刻开始。 docs : format('E')
代表星期几。因此,您的差异计算在一周的哪一天,必须在1到7之间。
From the moment.js docs: format('E')
stands for day of week. thus your diff is being computed on which day of the week, which has to be between 1 and 7.
从moment.js文档再次,这是他们的建议:
From the moment.js docs again, here is what they suggest:
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // 1
这是一个JSFiddle对于您的特定情况:
Here is a JSFiddle for your particular case:
$('#test').click(function() {
var startDate = moment("13.04.2016", "DD.MM.YYYY");
var endDate = moment("28.04.2016", "DD.MM.YYYY");
var result = 'Diff: ' + endDate.diff(startDate, 'days');
$('#result').html(result);
});
#test {
width: 100px;
height: 100px;
background: #ffb;
padding: 10px;
border: 2px solid #999;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.js"></script>
<div id='test'>Click Me!!!</div>
<div id='result'></div>
这篇关于Moment.js - 两天的天数差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!