momentjs不会在两个日期之间得到差异

时间:2019-11-24 16:16:58

标签: momentjs

我试图以分钟为单位得出现在和结束日期之间的差额。我有两个日期变量,但是当我尝试将它们相减时,它说Property 'diff' does not exist on type 'string'.

console.log(现在)输出:November 24th 2019, 11:13:32

console.log(endDate)输出:November 24th 2019, 12:25:10

所以值是日期格式。

感谢您的帮助

let endDateTime = moment
  .unix(parseInt(auctionEndDateTime))
  .format("MMMM Do YYYY, h:mm:ss");


let start=moment(Date.now());
let end=moment(endDateTime);
let duration = moment.duration(end.diff(start));
let hours = duration.asHours();


console.log('hours ' + hours);
console.log('days ' + duration.asDays());

1 个答案:

答案 0 :(得分:1)

// you can get the difference between two days with javascript Date class

let firstDate = new Date('Sun Nov 24 2019 17:28:33'); //new Date('2019-11-12');
let secondDate = new Date('Tue Nov 26 2019 17:28:33');//new Date('2019-11-20');

let milliSFirst = firstDate.getTime();
let milliSSecond = secondDate.getTime();

console.log("diff in days " + (milliSSecond - milliSFirst)/(1000 * 3600 * 24) )

// take the dates as milliseconds and then you can do the calculations

let start=moment(Date.now());
let end=moment(Date.now() + 1000 * 3600 * 24 );
let duration = moment.duration(end.diff(start));
let hours = duration.asHours();
 
 
console.log('hours ' + hours);
console.log('days ' + duration.asDays());
<script src="https://rawgit.com/moment/moment/2.2.1/min/moment.min.js"></script>