【问题标题】:Time calculation with milliseconds in JSJS中以毫秒为单位的时间计算
【发布时间】:2021-01-21 08:06:35
【问题描述】:

我想在 Javascript 中找出两个毫秒值之间的差异。 正如您在下面的快照中看到的,我在 Excel 中计算了两个时间值。 我的期望与 JS 代码的计算值完全相同。 我尝试了一些代码 sn-p,但我在几秒钟内得到了细微的差别。

var d1 = '2020-12-15 01:00:23.788';
var d2 = '2020-12-15 01:00:55.482';
var date1 = new Date(d1);
var date2 = new Date(d2);
//date2 += 500;
//date2 = new Date(date2);
//date2.setMilliseconds(5);
var date1_ms = date1.getTime();
var date2_ms = date2.getTime();
// Calculate the difference in milliseconds
var difference_ms = date2_ms - date1_ms;
//take out milliseconds
difference_ms = difference_ms / 1000;
var seconds = Math.floor(difference_ms % 60);
difference_ms = difference_ms / 60;
var minutes = Math.floor(difference_ms % 60);
difference_ms = difference_ms / 60;
var hours = Math.floor(difference_ms % 24);

var demo = hours + ' hours, ' + minutes + ' minutes, and ' + seconds + ' seconds.' + difference_ms;
document.getElementById("demo").innerHTML = demo;
<h2>JavaScript new Date()</h2>

<p>new Date() creates a new date object with the current date and time:</p>

<p id="demo"></p>

输出: new Date() 使用当前日期和时间创建一个新的日期对象: 0 小时 0 分 31 秒。0.008803888888888889

【问题讨论】:

    标签: javascript


    【解决方案1】:

    正确实现时,JS 会做同样的事情

    我尝试了更有趣的时间

    // Excel: 02:10:55,482 - 01:09:23,788 = 01:01:31,694
    
    const fmtTime = date => {
      const hours = `0${date.getHours() - 1}`.slice(-2);
      const minutes = `0${date.getMinutes()}`.slice(-2);
      const seconds = `0${date.getSeconds()}`.slice(-2);
      const ms = `00${date.getMilliseconds()}`.slice(-3);
      return `${hours}:${minutes}:${seconds}.${ms}`
    }
    
    
    const from = "01:09:23,788"
    const to = "02:10:55.482"
    const re = /(\d{2}):(\d{2}):(\d{2}).(\d{3})/;
    const [m1, fromhh, frommm, fromss, fromms] = from.match(re);
    const [m2, tohh, tomm, toss, tomms] = to.match(re);
    
    // method one
    
    let d = new Date()
    d.setHours(fromhh, frommm, fromss, fromms)
    const fromTime = d.getTime()
    d.setHours(tohh, tomm, toss, tomms)
    const toTime = d.getTime()
    const diffInMS1 = toTime - fromTime
    console.log(diffInMS1)
    
    d = new Date(diffInMS1);
    console.log(fmtTime(d))
    
    
    // Method 2 - Note I need to cast to int where I only add (+fromms)
    let fromMS = (fromhh * 60 * 60 * 1000) + (frommm * 60 * 1000) + (fromss * 1000) + +fromms;
    let toMS = (tohh * 60 * 60 * 1000) + (tomm * 60 * 1000) + (toss * 1000) + +tomms;
    const diffInMS2 = toMS - fromMS;
    console.log(diffInMS2)
    
    
    d = new Date(diffInMS2);
    console.log(fmtTime(d))

    【讨论】:

      【解决方案2】:

      function splitInNumberArray(str) {
        return str
          .replace(/(:|\.)/g, " ")
          .split(" ")
          .map((x) => parseInt(x));
      }
      
      function convertToMilliseconds(timeArray) {
        return (
          timeArray[0] * 60 * 60 * 1000 +
          timeArray[1] * 60 * 1000 +
          timeArray[2] * 1000 +
          timeArray[3]
        );
      }
      
      function msToTime(duration) {
        var milliseconds = parseInt((duration % 1000) / 100),
          seconds = Math.floor((duration / 1000) % 60),
          minutes = Math.floor((duration / (1000 * 60)) % 60),
          hours = Math.floor((duration / (1000 * 60 * 60)) % 24);
      
        hours = hours < 10 ? "0" + hours : hours;
        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;
      
        return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
      }
      
      // This function is taken from https://stackoverflow.com/questions/19700283/how-to-convert-time-milliseconds-to-hours-min-sec-format-in-javascript
      function parseDuration(duration) {
        let remain = duration;
      
        let hours = Math.floor(remain / (1000 * 60 * 60));
        remain = remain % (1000 * 60 * 60);
      
        let minutes = Math.floor(remain / (1000 * 60));
        remain = remain % (1000 * 60);
      
        let seconds = Math.floor(remain / 1000);
        remain = remain % 1000;
      
        let milliseconds = remain;
      
        return {
          hours,
          minutes,
          seconds,
          milliseconds,
        };
      }
      
      function minTwoDigits(n) {
        return (n < 10 ? "0" : "") + n;
      }
      
      //***************************************
      const time1 = "01:00:55.482";
      const time2 = "01:00:23.788";
      
      const numberArray1 = splitInNumberArray(time1);
      const numberArray2 = splitInNumberArray(time2);
      
      const msTime1 = convertToMilliseconds(numberArray1);
      const msTime2 = convertToMilliseconds(numberArray2);
      
      const diff = msTime1 - msTime2;
      const { hours, minutes, seconds, milliseconds } = parseDuration(diff);
      console.log(
        `${time1} - ${time2} = ${minTwoDigits(hours)}:${minTwoDigits(
          minutes
        )}:${minTwoDigits(seconds)}.${milliseconds}`
      );

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-02-06
        • 2012-11-15
        • 1970-01-01
        • 2013-08-29
        • 2010-11-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多