两个日期之间的差异moment.js

时间:2018-04-27 08:51:31

标签: angularjs momentjs

我有一个格式化的date字符串"19/04/2018"我需要将它与今天的日期进行比较,并知道已经过了多少天。

我正在尝试这种方式,但它无法正常工作。

var stringDate =  $scope.dataAddOutpatient.date; //Return "19/04/2018" 
var today = moment().format("DD/MM/YYYY");
var date = moment(stringDate);

//Difference in number of days
var dates = moment.duration(date.diff(today)).asDays();

始终return 0。怎么了?

在我看到的比较类型字符串的对象的示例中,我需要将其与类型时刻的对象进行比较。

3 个答案:

答案 0 :(得分:0)



$('#test').click(function() {
    var startDate = moment("13/04/2016", "DD/MM/YYYY");
	var currenDate = moment(new Date()).format("DD/MM/YYYY");
	var endDate = moment(currenDate, "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>
&#13;
&#13;
&#13;

了解更多信息 - moment js - two dates difference in number of days

答案 1 :(得分:0)

根据moment.js documentation,让我们检查一下他们的建议:

var dateA = moment([2007, 0, 29]);
var dateB = moment([2007, 0, 28]);
dateA.diff(dateB, 'days'); // result is 1

尝试这种方式,可能会解决您的问题。

答案 2 :(得分:0)

var toDay= moment();
var startDate = moment('2017-11-09');
console.log('Milliseconds:',toDay.diff(startDate));
console.log('days:', toDay.diff(startDate, 'days'), 'days');
console.log('months:', toDay.diff(startDate, 'months'));