Calculate Time Difference with JavaScript

后端 未结 12 1085
有刺的猬
有刺的猬 2020-12-01 13:20

I have two HTML input boxes, that need to calculate the time difference in JavaScript onBlur (since I need it in real time) and insert the result to new input box.

F

相关标签:
12条回答
  • 2020-12-01 13:42

    Depending on what you allow to enter, this one will work. There may be some boundary issues if you want to allow 1am to 1pm

    NOTE: This is NOT using a date objects or moment.js

    function pad(num) {
      return ("0"+num).slice(-2);
    }
    function diffTime(start,end) {
      var s = start.split(":"), sMin = +s[1] + s[0]*60,
          e =   end.split(":"), eMin = +e[1] + e[0]*60,
       diff = eMin-sMin;
      if (diff<0) { sMin-=12*60;  diff = eMin-sMin }
      var h = Math.floor(diff / 60),
          m = diff % 60;
      return "" + pad(h) + ":" + pad(m);
    }  
    document.getElementById('button').onclick=function() {
      document.getElementById('delay').value=diffTime(
          document.getElementById('timeOfCall').value, 
          document.getElementById('timeOfResponse').value
      );
    }
    <input type="time" id="timeOfCall">
    <input type="time" id="timeOfResponse">
    <button type="button" id="button">CLICK</button>
    <input type="time" id="delay">

    0 讨论(0)
  • 2020-12-01 13:42

    tl;dr

    One off run

    const t1 = new Date(1579876543210) // your initial time
    const t2 = new Date(1579987654321) // your later time
    
    const diff = t2-t1
    const SEC = 1000, MIN = 60 * SEC, HRS = 60 * MIN
    const humanDiff = `${Math.floor(diff/HRS)}:${Math.floor((diff%HRS)/MIN).toLocaleString('en-US', {minimumIntegerDigits: 2})}:${Math.floor((diff%MIN)/SEC).toLocaleString('en-US', {minimumIntegerDigits: 2})}.${Math.floor(diff % SEC).toLocaleString('en-US', {minimumIntegerDigits: 4, useGrouping: false})}`
    
    console.log("humanDiff:", humanDiff)
    // > humanDiff: 30:51:51.0111

    As a function

    function humanDiff (t1, t2) {
      const diff = Math.max(t1,t2) - Math.min(t1,t2) 
      const SEC = 1000, MIN = 60 * SEC, HRS = 60 * MIN
      
      const hrs = Math.floor(diff/HRS)
      const min = Math.floor((diff%HRS)/MIN).toLocaleString('en-US', {minimumIntegerDigits: 2})
      const sec = Math.floor((diff%MIN)/SEC).toLocaleString('en-US', {minimumIntegerDigits: 2})
      const ms = Math.floor(diff % SEC).toLocaleString('en-US', {minimumIntegerDigits: 4, useGrouping: false})
      
      return `${hrs}:${min}:${sec}.${ms}`
    }
    
    const t1 = new Date(1579876543210)
    const t2 = new Date(1579987654321)
    
    console.log("humanDiff(t1, t2):", humanDiff(t1, t2))
    // > humanDiff: 30:51:51.0111

    Explanation

    Adjust humanDiff for your maximum and minimum reportable increments and formatting needs:

    const t1 = new Date(1579876543210) // Set your initial time (`t1`)
    const t2 = new Date(1579986654321) // , conclusion time (`t2`), and
    const diff = t2-t1 // calculate their difference in milliseconds
    console.log("         t2:", t2.toISOString()) // >   t2: 2020-01-25T21:27:34.321Z
    console.log("         t1:", t1.toISOString()) // >   t1: 2020-01-24T14:35:43.210Z
    console.log("       diff:", diff)             // > diff: 111111111
    
    // Set your constant time values for easy readability
    const SEC = 1000
    const MIN = 60 * SEC
    const HRS = 60 * MIN
    
    /* For a given unit
    1) disregard any previously relevant units, e.g. to calculate minutes, we can
       disregard all hours & focus on only the remainder - `(diff%HRS)`
    2) divide the remainder by the given unit, e.g. for minutes, `(diff%HRS)/MIN`
    3) disregard any remainder, e.g. again for minutes, `Math.floor((diff%HRS)/MIN)`
    NOTE: for your maximum unit (HRS in the examples below) you probably _don't_
      want to disregard high values, e.g. If the difference is >24 hrs and something,
      you should either include a DAYS value, or simply display 30 hrs */
    let hrs = Math.floor(diff/HRS)
    let min = Math.floor((diff%HRS)/MIN)
    let sec = Math.floor((diff%MIN)/SEC)
    let ms  = Math.floor(diff % SEC) // just the remainder 
              // BUT ms IS NOT ACTUALLY CORRECT, see humanDiff_3 for the fix ;-)
    let humanDiff_1 = `${hrs}:${min}:${sec}.${ms}`
    console.log("humanDiff_1:", humanDiff_1)
    // > humanDiff_1: 30:51:51.111
    
    sec = Math.round((diff%MIN)/SEC) // can also just round the last unit
    const humanDiff_2 = `${hrs} hrs ${min} mins & ${sec} secs`
    console.log("humanDiff_2:", humanDiff_2)
    // > humanDiff_2: 30 hrs 51 mins & 51 secs
    
    /* To ensure a set number of digits, format the numbers with `toLocaleString`'s
       `minimumIntegerDigits`, if more than 3 digits, also use its `useGrouping`   */
    hrs = Math.floor(diff/HRS)
    min = Math.floor((diff%HRS)/MIN).toLocaleString('en-US', {minimumIntegerDigits: 2})
    sec = Math.floor((diff%MIN)/SEC).toLocaleString('en-US', {minimumIntegerDigits: 2})
    ms = Math.floor(diff % SEC).toLocaleString('en-US', {minimumIntegerDigits: 4, useGrouping: false})
    
    const humanDiff_3 = `${hrs}:${min}:${sec}.${ms}`
    console.log("humanDiff_3:", humanDiff_3)
    // > humanDiff_3: 30:51:51.0111
    // NOTE: milliseconds are now 4 digits

    0 讨论(0)
  • 2020-12-01 13:47

    Try This

    var dif = ( new Date("1970-1-1 " + end-time) - new Date("1970-1-1 " + start-time) ) / 1000 / 60 / 60;
    
    0 讨论(0)
  • 2020-12-01 13:47

    This is an updated version of one that was already submitted. It is with the seconds.

    function diff(start, end) {
        start = start.split(":");
        end = end.split(":");
        var startDate = new Date(0, 0, 0, start[0], start[1], 0);
        var endDate = new Date(0, 0, 0, end[0], end[1], 0);
        var diff = endDate.getTime() - startDate.getTime();
        var hours = Math.floor(diff / 1000 / 60 / 60);
        diff -= hours * (1000 * 60 * 60);
        var minutes = Math.floor(diff / 1000 / 60);
        diff -= minutes * (1000 * 60);
        var seconds = Math.floor(diff / 1000);
    
        // If using time pickers with 24 hours format, add the below line get exact hours
        if (hours < 0)
           hours = hours + 24;
    
        return (hours <= 9 ? "0" : "") + hours + ":" + (minutes <= 9 ? "0" : "") + minutes + (seconds<= 9 ? "0" : "") + seconds;
    }
    

    My Updated Version:

    Allows for you to convert the dates into milliseconds and go off of that instead of splitting.

    Example Does -- Years/Months/Weeks/Days/Hours/Minutes/Seconds

    Example: https://jsfiddle.net/jff7ncyk/308/

    0 讨论(0)
  • 2020-12-01 13:49

    Here is one possible solution:

    function diff(start, end) {
        start = start.split(":");
        end = end.split(":");
        var startDate = new Date(0, 0, 0, start[0], start[1], 0);
        var endDate = new Date(0, 0, 0, end[0], end[1], 0);
        var diff = endDate.getTime() - startDate.getTime();
        var hours = Math.floor(diff / 1000 / 60 / 60);
        diff -= hours * 1000 * 60 * 60;
        var minutes = Math.floor(diff / 1000 / 60);
    
        // If using time pickers with 24 hours format, add the below line get exact hours
        if (hours < 0)
           hours = hours + 24;
    
        return (hours <= 9 ? "0" : "") + hours + ":" + (minutes <= 9 ? "0" : "") + minutes;
    }
    

    DEMO: http://jsfiddle.net/KQQqp/

    0 讨论(0)
  • 2020-12-01 13:55

    Try this: actually this a problem from codeeval.com

    I solved it in this way .

    This program takes a file as the argument so i used a little node js to read the file.

    Here is my code.

    var fs  = require("fs");
    fs.readFileSync(process.argv[2]).toString().split('\n').forEach(function (line) {
        if (line !== "") {
            var arr = line.split(" ");
            var arr1 = arr[0].split(":");
            var arr2 = arr[1].split(":");
            var time1 = parseInt(arr1[0])*3600 + parseInt(arr1[1])*60 + parseInt(arr1[2]);
            var time2 = parseInt(arr2[0])*3600 + parseInt(arr2[1])*60 + parseInt(arr2[2]);
            var dif = Math.max(time1,time2) - Math.min(time1,time2);
            var ans = [];
            ans[0] = Math.floor(dif/3600);
            if(ans[0]<10){ans[0] = "0"+ans[0]}
            dif = dif%3600;
            ans[1] = Math.floor(dif/60);
            if(ans[1]<10){ans[1] = "0"+ans[1]}
            ans[2] = dif%60;
            if(ans[2]<10){ans[2] = "0"+ans[2]}
            console.log(ans.join(":"));
        }
    });
    
    0 讨论(0)
提交回复
热议问题