Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
527 views
in Technique[技术] by (71.8m points)

javascript - 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') );

Between 13.04.2016 and 28.04.2016 I shouldn't get that difference is 3 or 2 days...

I've tried to multiple combinations:

  • swap startDate.diff(endDate) with endDate.diff(startDate)
  • format('E') with something I've come up searching the SO

result: all the time I get that difference is 3 or 2 days.

What am I doing wrong? Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...