How to calculate date difference in JavaScript?

前端 未结 18 1745
执笔经年
执笔经年 2020-11-22 03:41

I want to calculate date difference in days, hours, minutes, seconds, milliseconds, nanoseconds. How can I do it?

相关标签:
18条回答
  • 2020-11-22 03:58
    <html lang="en">
    <head>
    <script>
    function getDateDiff(time1, time2) {
      var str1= time1.split('/');
      var str2= time2.split('/');
    
      //                yyyy   , mm       , dd
      var t1 = new Date(str1[2], str1[0]-1, str1[1]);
      var t2 = new Date(str2[2], str2[0]-1, str2[1]);
    
      var diffMS = t1 - t2;    
      console.log(diffMS + ' ms');
    
      var diffS = diffMS / 1000;    
      console.log(diffS + ' ');
    
      var diffM = diffS / 60;
      console.log(diffM + ' minutes');
    
      var diffH = diffM / 60;
      console.log(diffH + ' hours');
    
      var diffD = diffH / 24;
      console.log(diffD + ' days');
      alert(diffD);
    }
    
    //alert(getDateDiff('10/18/2013','10/14/2013'));
    </script>
    </head>
    <body>
      <input type="button" 
           onclick="getDateDiff('10/18/2013','10/14/2013')" 
           value="clickHere()" />
    
    </body>
    </html>
    
    0 讨论(0)
  • 2020-11-22 04:05

    Another solution is convert difference to a new Date object and get that date's year(diff from 1970), month, day etc.

    var date1 = new Date(2010, 6, 17);
    var date2 = new Date(2013, 12, 18);
    var diff = new Date(date2.getTime() - date1.getTime());
    // diff is: Thu Jul 05 1973 04:00:00 GMT+0300 (EEST)
    
    console.log(diff.getUTCFullYear() - 1970); // Gives difference as year
    // 3
    
    console.log(diff.getUTCMonth()); // Gives month count of difference
    // 6
    
    console.log(diff.getUTCDate() - 1); // Gives day count of difference
    // 4
    

    So difference is like "3 years and 6 months and 4 days". If you want to take difference in a human readable style, that can help you.

    0 讨论(0)
  • 2020-11-22 04:05

    function daysInMonth (month, year) {
        return new Date(year, month, 0).getDate();
    }
    function getduration(){
    
    let A= document.getElementById("date1_id").value
    let B= document.getElementById("date2_id").value
    
    let C=Number(A.substring(3,5))
    let D=Number(B.substring(3,5))
    let dif=D-C
    let arr=[];
    let sum=0;
    for (let i=0;i<dif+1;i++){
      sum+=Number(daysInMonth(i+C,2019))
    }
    let sum_alter=0;
    for (let i=0;i<dif;i++){
      sum_alter+=Number(daysInMonth(i+C,2019))
    }
    let no_of_month=(Number(B.substring(3,5)) - Number(A.substring(3,5)))
    let days=[];
    if ((Number(B.substring(3,5)) - Number(A.substring(3,5)))>0||Number(B.substring(0,2)) - Number(A.substring(0,2))<0){
    days=Number(B.substring(0,2)) - Number(A.substring(0,2)) + sum_alter
    }
    
    if ((Number(B.substring(3,5)) == Number(A.substring(3,5)))){
    console.log(Number(B.substring(0,2)) - Number(A.substring(0,2)) + sum_alter)
    }
    
    time_1=[]; time_2=[]; let hour=[];
     time_1=document.getElementById("time1_id").value
     time_2=document.getElementById("time2_id").value
      if (time_1.substring(0,2)=="12"){
         time_1="00:00:00 PM"
      }
    if (time_1.substring(9,11)==time_2.substring(9,11)){
    hour=Math.abs(Number(time_2.substring(0,2)) - Number(time_1.substring(0,2)))
    }
    if (time_1.substring(9,11)!=time_2.substring(9,11)){
    hour=Math.abs(Number(time_2.substring(0,2)) - Number(time_1.substring(0,2)))+12
    }
    let min=Math.abs(Number(time_1.substring(3,5))-Number(time_2.substring(3,5)))
    document.getElementById("duration_id").value=days +" days "+ hour+"  hour " + min+"  min " 
    }
    <input type="text" id="date1_id" placeholder="28/05/2019">
    <input type="text" id="date2_id" placeholder="29/06/2019">
    <br><br>
    <input type="text" id="time1_id" placeholder="08:01:00 AM">
    <input type="text" id="time2_id" placeholder="00:00:00 PM">
    <br><br>
    <button class="text" onClick="getduration()">Submit </button>
    <br><br>
    <input type="text" id="duration_id" placeholder="days hour min">

    0 讨论(0)
  • 2020-11-22 04:05

    this should work just fine if you just need to show what time left, since JavaScript uses frames for its time you'll have get your End Time - The Time RN after that we can divide it by 1000 since apparently 1000 frames = 1 seconds, after that you can use the basic math of time, but there's still a problem to this code, since the calculation is static, it can't compensate for the different day total in a year (360/365/366), the bunch of IF after the calculation is to make it null if the time is lower than 0, hope this helps even though it's not exactly what you're asking :)

    var now = new Date();
    var end = new Date("End Time");
    var total = (end - now) ;
    var totalD =  Math.abs(Math.floor(total/1000));
    
    var years = Math.floor(totalD / (365*60*60*24));
    var months = Math.floor((totalD - years*365*60*60*24) / (30*60*60*24));
    var days = Math.floor((totalD - years*365*60*60*24 - months*30*60*60*24)/ (60*60*24));
    var hours = Math.floor((totalD - years*365*60*60*24 - months*30*60*60*24 - days*60*60*24)/ (60*60));
    var minutes = Math.floor((totalD - years*365*60*60*24 - months*30*60*60*24 - days*60*60*24 - hours*60*60)/ (60));
    var seconds = Math.floor(totalD - years*365*60*60*24 - months*30*60*60*24 - days*60*60*24 - hours*60*60 - minutes*60);
    
    var Y = years < 1 ? "" : years + " Years ";
    var M = months < 1 ? "" : months + " Months ";
    var D = days < 1 ? "" : days + " Days ";
    var H = hours < 1 ? "" : hours + " Hours ";
    var I = minutes < 1 ? "" : minutes + " Minutes ";
    var S = seconds < 1 ? "" : seconds + " Seconds ";
    var A = years == 0 && months == 0 && days == 0 && hours == 0 && minutes == 0 && seconds == 0 ? "Sending" : " Remaining";
    
    document.getElementById('txt').innerHTML = Y + M + D + H + I + S + A;
    
    0 讨论(0)
  • 2020-11-22 04:06

    Sorry but flat millisecond calculation is not reliable Thanks for all the responses, but few of the functions I tried are failing either on 1. A date near today's date 2. A date in 1970 or 3. A date in a leap year.

    Approach that best worked for me and covers all scenario e.g. leap year, near date in 1970, feb 29 etc.

    var someday = new Date("8/1/1985");
    var today = new Date();
    var years = today.getFullYear() - someday.getFullYear();
    
    // Reset someday to the current year.
    someday.setFullYear(today.getFullYear());
    
    // Depending on when that day falls for this year, subtract 1.
    if (today < someday)
    {
        years--;
    }
    document.write("Its been " + years + " full years.");
    
    0 讨论(0)
  • 2020-11-22 04:08

    use Moment.js for all your JavaScript related date-time calculation

    Answer to your question is:

    var a = moment([2007, 0, 29]);   
    var b = moment([2007, 0, 28]);    
    a.diff(b) // 86400000  
    

    Complete details can be found here

    0 讨论(0)
提交回复
热议问题