javascript 使用javascript的时间总和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26056434/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:25:36  来源:igfitidea点击:

Sum of Time using javascript

javascriptjquery

提问by Satnam singh

How to of sum time in javascript

如何在javascript中求和时间

01:00:00
00:30:00
00:30:00

I have time like above i want sum of given time like

我有时间像上面一样我想要给定时间的总和

sum of above time= 02:00:00

if i use javascript method setHours(),setMinutes() these function replace old time and show newly added time like :

如果我使用 javascript 方法 setHours(),setMinutes() 这些函数替换旧时间并显示新添加的时间,如:

1. new Date( new Date(0, 0, 0, 00, 00, 00, 0)).setMinutes(30)
2. new Date(new Date( new Date(0, 0, 0, 00, 00, 00, 0)).setMinutes(30)).setMinutes(30);

these above both condition result is same but i want here 00:30 + 00:30 = 01:00

以上两个条件结果相同,但我想要这里 00:30 + 00:30 = 01:00

. Please help thanks in advance

. 请帮助提前致谢

回答by minikomi

Some functions to help you go back and forth between the formatted length of time and seconds as an integer:

一些函数可以帮助您在格式化的时间长度和整数秒之间来回切换:

function timestrToSec(timestr) {
  var parts = timestr.split(":");
  return (parts[0] * 3600) +
         (parts[1] * 60) +
         (+parts[2]);
}

function pad(num) {
  if(num < 10) {
    return "0" + num;
  } else {
    return "" + num;
  }
}

function formatTime(seconds) {
  return [pad(Math.floor(seconds/3600)),
          pad(Math.floor(seconds/60)%60),
          pad(seconds%60),
          ].join(":");
}

You can use them to achieve what you want:

您可以使用它们来实现您想要的:

time1 = "02:32:12";
time2 = "12:42:12";
formatTime(timestrToSec(time1) + timestrToSec(time2));
// => "15:14:24"

回答by Bhushan Kawadkar

Try this :

试试这个 :

        var time1 = "01:00:00";
        var time2 = "00:30:00";
        var time3 = "00:30:00";
        
        var hour=0;
        var minute=0;
        var second=0;
        
        var splitTime1= time1.split(':');
        var splitTime2= time2.split(':');
        var splitTime3= time3.split(':');
        
        hour = parseInt(splitTime1[0])+parseInt(splitTime2[0])+parseInt(splitTime3[0]);
        minute = parseInt(splitTime1[1])+parseInt(splitTime2[1])+parseInt(splitTime3[1]);
        hour = hour + minute/60;
        minute = minute%60;
        second = parseInt(splitTime1[2])+parseInt(splitTime2[2])+parseInt(splitTime3[2]);
        minute = minute + second/60;
        second = second%60;
        
        alert('sum of above time= '+hour+':'+minute+':'+second);

回答by T.J. Crowder

If you want to use a Dateobject for this, you can, you just have to be sure to include the currentvalue for the unit you're changing when adding to it, like so:

如果你想为此使用一个Date对象,你可以,你只需要确保在添加时包含你正在更改的单位的当前值,如下所示:

var dt = new Date(0, 0, 0, 0, 0, 0, 0);
dt.setHours(dt.getHours() + 1);      // For the 01:00
dt.setMinutes(dt.getMinutes() + 30); // For the first 00:30
dt.setMinutes(dt.getMinutes() + 30); // For the second 00:30

display("Hours: " + dt.getHours());
display("Minutes: " + dt.getMinutes());

function display(msg) {
  var p = document.createElement("p");
  p.innerHTML = String(msg);
  document.body.appendChild(p);
}

Technically, of course, the first time you know getHoursand getMinuteswill return 0, but for consistency, best to just always include them.

从技术上说,当然,你第一次知道getHoursgetMinutes会返回0,但为了保持一致性,最好还是始终包含它们。

回答by Matteo Gobbo

This solution is perfect:

这个解决方案是完美的:

function timestrToSec(timestr) {
  var parts = timestr.split(":");
  return (parts[0] * 3600) +
         (parts[1] * 60) +
         (+parts[2]);
}

function pad(num) {
  if(num < 10) {
    return "0" + num;
  } else {
    return "" + num;
  }
}

function formatTime(seconds) {
  return [pad(Math.floor(seconds/3600)%60),
          pad(Math.floor(seconds/60)%60),
          pad(seconds%60),
          ].join(":");
}

but there is a little bug in the last function "formatTime" !

但是最后一个函数“formatTime”有一个小错误!

return [pad(Math.floor(seconds/3600)%60), => return [pad(Math.floor(seconds/3600)),

so without %60!! Becouse if i have to sum hour, it can be greater than 60 (H)

所以没有 %60!!因为如果我必须求和小时,它可以大于 60 (H)

回答by BX16Soupapes

This work for me:

这对我有用:

    function padnum(n){return n<10 ? '0'+n : n}

    var time1 = "00:30";
    var time2 = "00:60";

    var minute=0;
    var second=0;

    var splitTime1= time1.split(':');
    var splitTime2= time2.split(':');

    minute = parseInt(parseInt(splitTime1[0]))+parseInt(splitTime2[0]);
    second = parseInt(parseInt(splitTime1[1]))+parseInt(splitTime2[1]);

    minute = minute + second/60;
    minute =parseInt(minute);
    second = second%60;

    minute = padnum(minute);
    second = padnum(second);        

    alert('sum of above time= '+minute+':'+second);

回答by Diego Fortes

Here is a function with error handling included.

这是一个包含错误处理的函数。

Even though it's a big function it results in an useful one-liner. Just pass an array with values and you're good to go.

尽管它是一个很大的函数,但它会产生一个有用的单行。只需传递一个带有值的数组就可以了。

function sumMinutes(values) {

  const validate = time => {
    if (time > 59 || time < 0) {
      throw new Error(
        "Hours, minutes and seconds values have to be between 0 and 59."
      );
    }
    return time;
  };

  const seconds = values
    .map(e => validate(Number(e.split(":").reverse()[0])))
    .reduce((a, b) => a + b);

  let minutes = values
    .map(e => Number(e.split(":").reverse()[1]))
    .reduce((a, b) => a + b);

  let hours = values
    .map(e =>
      e.split(":").reverse()[2] ? Number(e.split(":").reverse()[2]) : 0
    )
    .reduce((a, b) => a + b);

  minutes *= 60;
  hours *= 3600;

  let result = new Date((hours + minutes + seconds) * 1000)
    .toISOString()
    .substr(11, 8);

  return result.split(":").reverse()[2] === "00" ? result.slice(3) : result;
}

/* examples */
const seconds = ["00:03", "00:9"];
const mins = ["01:20", "1:23"];
const hours = ["00:03:59", "02:05:01"];
const mix = ["00:04:58", "10:00"];

console.log(sumMinutes(seconds)); //'00:12'
console.log(sumMinutes(mins)); //'02:43'
console.log(sumMinutes(hours)); //'02:09:00'
console.log(sumMinutes(mix)); //'14:58'