Check time difference in Javascript

后端 未结 18 1140
梦毁少年i
梦毁少年i 2020-11-22 04:27

How would you check time difference from two text-boxes in Javascript?

相关标签:
18条回答
  • 2020-11-22 04:37

    This is an addition to dmd733's answer. I fixed the bug with Day duration (well I hope I did, haven't been able to test every case).

    I also quickly added a String property to the result that holds the general time passed (sorry for the bad nested ifs!!). For example if used for UI and indicating when something was updated (like a RSS feed). Kind of out of place but nice-to-have:

    function getTimeDiffAndPrettyText(oDatePublished) {
    
      var oResult = {};
    
      var oToday = new Date();
    
      var nDiff = oToday.getTime() - oDatePublished.getTime();
    
      // Get diff in days
      oResult.days = Math.floor(nDiff / 1000 / 60 / 60 / 24);
      nDiff -= oResult.days * 1000 * 60 * 60 * 24;
    
      // Get diff in hours
      oResult.hours = Math.floor(nDiff / 1000 / 60 / 60);
      nDiff -= oResult.hours * 1000 * 60 * 60;
    
      // Get diff in minutes
      oResult.minutes = Math.floor(nDiff / 1000 / 60);
      nDiff -= oResult.minutes * 1000 * 60;
    
      // Get diff in seconds
      oResult.seconds = Math.floor(nDiff / 1000);
    
      // Render the diffs into friendly duration string
    
      // Days
      var sDays = '00';
      if (oResult.days > 0) {
          sDays = String(oResult.days);
      }
      if (sDays.length === 1) {
          sDays = '0' + sDays;
      }
    
      // Format Hours
      var sHour = '00';
      if (oResult.hours > 0) {
          sHour = String(oResult.hours);
      }
      if (sHour.length === 1) {
          sHour = '0' + sHour;
      }
    
      //  Format Minutes
      var sMins = '00';
      if (oResult.minutes > 0) {
          sMins = String(oResult.minutes);
      }
      if (sMins.length === 1) {
          sMins = '0' + sMins;
      }
    
      //  Format Seconds
      var sSecs = '00';
      if (oResult.seconds > 0) {
          sSecs = String(oResult.seconds);
      }
      if (sSecs.length === 1) {
          sSecs = '0' + sSecs;
      }
    
      //  Set Duration
      var sDuration = sDays + ':' + sHour + ':' + sMins + ':' + sSecs;
      oResult.duration = sDuration;
    
      // Set friendly text for printing
      if(oResult.days === 0) {
    
          if(oResult.hours === 0) {
    
              if(oResult.minutes === 0) {
                  var sSecHolder = oResult.seconds > 1 ? 'Seconds' : 'Second';
                  oResult.friendlyNiceText = oResult.seconds + ' ' + sSecHolder + ' ago';
              } else { 
                  var sMinutesHolder = oResult.minutes > 1 ? 'Minutes' : 'Minute';
                  oResult.friendlyNiceText = oResult.minutes + ' ' + sMinutesHolder + ' ago';
              }
    
          } else {
              var sHourHolder = oResult.hours > 1 ? 'Hours' : 'Hour';
              oResult.friendlyNiceText = oResult.hours + ' ' + sHourHolder + ' ago';
          }
      } else { 
          var sDayHolder = oResult.days > 1 ? 'Days' : 'Day';
          oResult.friendlyNiceText = oResult.days + ' ' + sDayHolder + ' ago';
      }
    
      return oResult;
    }
    
    0 讨论(0)
  • 2020-11-22 04:39
    You can Get Two Time Different with this function. 
    

     /**
         * Get Two Time Different
         * @param join
         * @param lastSeen
         * @param now
         * @returns {string}
         */
        function getTimeDiff( join, lastSeen, now = false)
        {
            let t1 = new Date(join).getTime(), t2 = new Date(lastSeen).getTime(), milliseconds =0, time ='';
            if (now) t2 = Date.now();
            if( isNaN(t1) || isNaN(t2) ) return '';
            if (t1 < t2) milliseconds = t2 - t1; else milliseconds = t1 - t2;
            var days = Math.floor(milliseconds / 1000 / 60 / (60 * 24));
            var date_diff = new Date( milliseconds );
            if (days > 0) time += days + 'd ';
            if (date_diff.getHours() > 0) time += date_diff.getHours() + 'h ';
            if (date_diff.getMinutes() > 0) time += date_diff.getMinutes() + 'm ';
            if (date_diff.getSeconds() > 0) time += date_diff.getSeconds() + 's ';
            return time;
        }
        
        
        console.log(getTimeDiff(1578852606608, 1579530945513));
        

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

    Here is my rendition....

    function get_time_difference(earlierDate, laterDate) 
    {
        var oDiff = new Object();
    
        //  Calculate Differences
        //  -------------------------------------------------------------------  //
        var nTotalDiff = laterDate.getTime() - earlierDate.getTime();
    
        oDiff.days = Math.floor(nTotalDiff / 1000 / 60 / 60 / 24);
        nTotalDiff -= oDiff.days * 1000 * 60 * 60 * 24;
    
        oDiff.hours = Math.floor(nTotalDiff / 1000 / 60 / 60);
        nTotalDiff -= oDiff.hours * 1000 * 60 * 60;
    
        oDiff.minutes = Math.floor(nTotalDiff / 1000 / 60);
        nTotalDiff -= oDiff.minutes * 1000 * 60;
    
        oDiff.seconds = Math.floor(nTotalDiff / 1000);
        //  -------------------------------------------------------------------  //
    
        //  Format Duration
        //  -------------------------------------------------------------------  //
        //  Format Hours
        var hourtext = '00';
        if (oDiff.days > 0){ hourtext = String(oDiff.days);}
        if (hourtext.length == 1){hourtext = '0' + hourtext};
    
        //  Format Minutes
        var mintext = '00';
        if (oDiff.minutes > 0){ mintext = String(oDiff.minutes);}
        if (mintext.length == 1) { mintext = '0' + mintext };
    
        //  Format Seconds
        var sectext = '00';
        if (oDiff.seconds > 0) { sectext = String(oDiff.seconds); }
        if (sectext.length == 1) { sectext = '0' + sectext };
    
        //  Set Duration
        var sDuration = hourtext + ':' + mintext + ':' + sectext;
        oDiff.duration = sDuration;
        //  -------------------------------------------------------------------  //
    
        return oDiff;
    }
    
    0 讨论(0)
  • 2020-11-22 04:42

    Try This :

    function SumHours() {
      var smon = document.getElementById('sMon').value ;
      var fmon = document.getElementById('fMon').value ;
      var diff = 0 ;
      if (smon && fmon) {
        smon = ConvertToSeconds(smon);
        fmon = ConvertToSeconds(fmon);
        diff = Math.abs( fmon - smon ) ;
        console.log( 'time difference is : ' + secondsTohhmmss(diff) );
      }
    
      function ConvertToSeconds(time) {
        var splitTime = time.split(":");
        return splitTime[0] * 3600 + splitTime[1] * 60;
      }
    
      function secondsTohhmmss(secs) {
        var hours = parseInt(secs / 3600);
        var seconds = parseInt(secs % 3600);
        var minutes = parseInt(seconds / 60) ;
        return hours + "hours : " + minutes + "minutes ";
      }
    }
    <td>
      <input type="time" class="dataInput" id="sMon" onchange="SumHours();" />
    </td>
    
    <td>
      <input type="time" class="dataInputt" id="fMon" onchange="SumHours();"/>
    </td>

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

    I like doing it via Epoch.

    var now = new Date();
    var future = new Date(now.setMinutes(15));
    
    var futureEpoch = moment(future).unix();
    var nowEpoch = moment(now).unix();
    var differenceInEpoch = nowEpoch - scheduledEpoch ;
    
    console.log("futureEpoch        : " + futureEpoch);
    console.log("nowEpoch              : " + nowEpoch);
    console.log("differenceInEpoch     : " + differenceInEpoch);
    
    var diffTime = new Date(0); // The 0 there is the key, which sets the date to the epoch
    diffTime.setUTCSeconds(differenceInEpoch);
    console.log("new diffTime : " + diffTime);
    
    0 讨论(0)
  • 2020-11-22 04:43

    When i tried the difference between same time stamp it gave 0 Days 5 Hours 30 Minutes

    so to get it exactly i have subtracted 5 hours and 30 min

    function get_time_diff( datetime )
    {
    var datetime = typeof datetime !== 'undefined' ? datetime : "2014-01-01 01:02:03.123456";
    
    var datetime = new Date(datetime).getTime();
    var now = new Date().getTime();
    
    if( isNaN(datetime) )
    {
        return "";
    }
    
    console.log( datetime + " " + now);
    
    if (datetime < now) {
        var milisec_diff = now - datetime;
    }else{
        var milisec_diff = datetime - now;
    }
    
    var days = Math.floor(milisec_diff / 1000 / 60 / (60 * 24));
    
    var date_diff = new Date( milisec_diff );
    
    return days + "d "+ (date_diff.getHours() - 5) + "h " + (date_diff.getMinutes() - 30) + "m";
    }
    
    0 讨论(0)
提交回复
热议问题