繁体   English   中英

如何减少使用 Javascript 的时间?

[英]How to reduce time using Javascript?

如何使用reduce()计算以下数组中所有时间的总和(字符串格式)?

time["00:30", "01:45", "02:33"]

times.reduce((time, nextTime) => time + nextTime, 0)

我在想我需要split(":"), parseInt()和一些更多的计算,还是有更简单的方法来做到这一点?

如果你可以使用像moment.js这样的开放式 JavaScript 库,下面的代码很简单并且可以保留你的字符串格式化时间。

请注意,我将"00:00"作为默认值传递给reduce() ,以便从零基线计算时间,这也遵循我们将用于数组中所有其他值的字符串格式。

const times["00:30", "01:45", "02:33"]

const totalTime = times.reduce((time, nextTime) => {
  return moment(time, "hh:mm")
          .add(nextTime, "hh:mm")
          .format("hh:mm");
}, "00:00");

console.log("total time -->", totalTime);

// total time --> "04:48"

如果我们在reduce()中添加日志记录来查看值的累积:

"12:30"
"02:15"
"04:48"
"total time -->" "04:48"

请注意,第一次通过后的结果是“12:30”。 如果数组中的所有时间总和小于一个时钟小时,则最终结果对于您的特定用例可能是不可接受的。

这对我有用,这个 function 计时器需要 2 次 hh:mm:ss 并将其拆分、划分,然后将它们加在一起,然后再次将其格式化为 hh:mm:ss

function timer(tempo1, tempo2) {
  var array1 = tempo1.split(":");

  var tempo_seg1 =
    parseInt(array1[0]) * 3600 + parseInt(array1[1]) * 60 + parseInt(array1[2]);

  var array2 = tempo2.split(":");

  var tempo_seg2 =
    parseInt(array2[0]) * 3600 + parseInt(array2[1]) * 60 + parseInt(array2[2]);

  var tempofinal = parseInt(tempo_seg1) + parseInt(tempo_seg2);

  var hours = Math.floor(tempofinal / (60 * 60));

  var divisorMinutes = tempofinal % (60 * 60);

  var minutes = Math.floor(divisorMinutes / 60);

  var divisorSeconds = divisorMinutes % 60;

  var seconds = Math.ceil(divisorSeconds);

  var counter = "";

  if (hours < 10) {
    counter = "0" + hours + ":";
  } else {
    counter = hours + ":";
  }

  if (minutes < 10) {
    counter += "0" + minutes + ":";
  } else {
    counter += minutes + ":";
  }

  if (seconds < 10) {
    counter += "0" + seconds;
  } else {
    counter += seconds;
  }

  return counter;
}

export default timer;

在我的 React App 上,我使用这段代码来跟踪时间并添加它们调用计时器 function

const updateTime = () => {
    let times = [];
    let times2 = [];
    if (todos.length > 1) {
      for (let i = 0; i < todos.length; i++) {
        times.push(todos[i].time + ":00");
      }
      times2 = times[0];
      for (let i = 1; i < times.length; i++) {
        times2 = timer(times2, times[i]);
      }
      times2 = times2.substr(0, 5);
    } else if (todos.length == 1) times2 = todos[0].time;
    else times2 = "No tasks";
    return times2;
  };

我只想要 hh:mm 但为了将来在需要时实现秒数,我将添加“:00”(秒数),然后再次使用将其删除

times2 = times2.substr(0, 5);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM