要对两个数组中的时间字符串元素进行求和,您可以使用Moment.js库来处理时间和日期。下面是一个使用Moment.js和Angular 7的示例代码:
首先,确保您已经安装了Moment.js库。您可以使用以下命令来安装Moment.js:
npm install moment
然后,在您的Angular 7组件中,引入Moment.js库:
import * as moment from 'moment';
接下来,假设您有两个包含时间字符串的数组:array1
和array2
。您可以使用以下代码将它们的时间字符串元素进行求和:
// 定义两个数组
let array1 = ['09:30:00', '10:45:00', '12:15:00'];
let array2 = ['01:30:00', '02:15:00', '03:45:00'];
// 定义总秒数
let totalSeconds = 0;
// 对array1中的元素进行求和
for(let timeString of array1) {
let time = moment(timeString, 'HH:mm:ss');
let duration = moment.duration(time);
totalSeconds += duration.asSeconds();
}
// 对array2中的元素进行求和
for(let timeString of array2) {
let time = moment(timeString, 'HH:mm:ss');
let duration = moment.duration(time);
totalSeconds += duration.asSeconds();
}
// 将总秒数转换为时间字符串
let totalTime = moment.utc(totalSeconds * 1000).format('HH:mm:ss');
console.log(totalTime); // 输出: 07:15:00
在上面的代码中,我们使用Moment.js来解析时间字符串,并将它们转换为Moment对象。然后,我们使用moment.duration()
函数将每个时间字符串转换为持续时间,并将其转换为以秒为单位的总秒数。最后,我们使用moment.utc()
函数将总秒数转换回时间字符串。
希望这可以帮助到您!