代码之家  ›  专栏  ›  技术社区  ›  Abhijit Mondal Abhi

如何对数组中的时间字符串求和?

  •  5
  • Abhijit Mondal Abhi  · 技术社区  · 7 年前

    假设,我有一个不同时间字符串的数组。

    let a: any = ["7:20", "5:50", "6:30"];
    

    我想总结一下这些hh:mm时间字符串。我正在建立一个使用离子4(角)的应用程序。我已经用过了。但不幸的是,我找不到任何解决办法。

    更新: 预期结果: 7:20+5:50+6:30=19:40(时:33)

    5 回复  |  直到 7 年前
        1
  •  1
  •   antonku    7 年前

    你可以把时间当作 moment durations 可以总结如下:

    const any = ['7:20', '7:52', '5:03', '1:01', '9:02', '6:00'];
    
    const sum = any.reduce((acc, time) => acc.add(moment.duration(time)), moment.duration());
    
    console.log([Math.floor(sum.asHours()), sum.minutes()].join(':'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
        2
  •  3
  •   Mihai Alexandru-Ionut    7 年前

    你可以使用 reduce 方法通过传递 回调 功能。

    let arr= ["7:20", "5:50", "6:30"];
    toSeconds = (str) => {
       str = str.split(':');
       return (+str[0]) * 60 + (+str[1]);  
    }
    
    toHHss = (seconds) => {
       let minutes = parseInt(seconds/60);
       seconds = seconds - minutes*60;
       return minutes + ':' + seconds;
    }
    let result = arr.reduce((r,elem) => r + toSeconds(elem), 0);
    console.log(toHHss(result));
        3
  •  1
  •   Mosè Raguzzini    7 年前

    普通的javascript实现:

    const secondsToHm = s => ({
      hours: ((s - s % 3600) / 3600) % 60, 
      minutes: ((s - s % 60) / 60) % 60, 
    })
    
    let a = ["7:20", "5:50", "6:30"];
    let total = 0; 
    
    for(let i = 0; i < a.length; i++){
      const aSlice = a[i].split(':');
      const aSeconds = (+aSlice[0]) * 60 * 60 + (+aSlice[1]) * 60;
      total += aSeconds
    }
    
    console.log(`${secondsToHm(total).hours}:${secondsToHm(total).minutes}`);
        4
  •  1
  •   RobG    7 年前

    POJS解决方案非常简单:

    /* Add array of time strings in H:mm format
    ** @param {Array<string>} timeArray - Array of H:mm
    ** @returns {string} - sum of times in H:mm format
    */
    function addTimes(timeArray) {
      let mins = timeArray.reduce((acc, time) => {
        let [h, m] = time.split(':');
        acc += h*60 + m*1;
        return acc;
      }, 0);
      return (mins/60|0) + ':' + ('0'+(mins%60)).slice(-2);
    }
    
    // Example
    console.log(addTimes(["7:20", "5:03", "6:42"]));
        5
  •  0
  •   Praveen    7 年前

    可以使用moment.duration()获取数组中每个时间字符串的毫秒数,然后添加它们。

    a.reduce((acc, t) => acc.add(moment.duration(t)), moment.duration())