简体   繁体   English

Javascript:2 个日期之间的天数之差

[英]Javascript: Difference between days between 2 dates

I have date string 2022-01-03T00:00:00.000Z, i want to find the difference between today and this day in days.我有日期字符串 2022-01-03T00:00:00.000Z,我想找出今天和这一天之间的差异。 I tried this but not working as expected.我试过了,但没有按预期工作。

   var d1 = Date.now();
   var d2 = new Date('2020-01-03T00:00:00.000Z').getTime();
   console.log(d1);
   console.log(d2);


   var hours = hoursDiff(d1, d2);

   var daysDiff = Math.floor( hours / 24 );
   console.log(daysDiff);



  function hoursDiff(d1, d2) {
     var minutes = minutesDiff(d1, d2);
     var diff = Math.floor( minutes / 60 );
     return diff;
  }

 function minutesDiff(d1, d2) {
   var seconds = secondsDiff(d1, d2);
   var diff = Math.floor( seconds / 60 );
   return diff;
 }

  function secondsDiff(d1, d2) {
     var millisecondDiff = d2 - d1;
     var diff = Math.floor( ( d2 - d1) / 1000 );
     return diff;
   }

See comments in snippet:请参阅片段中的评论:

 var d = new Date(); // build a date with 0 hours, minutes, seconds var d1 = new Date(d.getFullYear() + '-' + ("0" + d.getMonth()).slice(-2) + '-' + d.getDate() + 'T00:00:00.000Z').getTime(); // date to compare var d2 = new Date('2022-04-27T00:00:00.000Z').getTime(); // to seconds / to minutes / to hours/ to days console.log((d1 - d2) / 1000 / 60 / 60 / 24);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM