一只小白的记录
data() {
return {
array: [
{ startTime: '09:30', endTime: '12:45' },
{ startTime: '14:00', endTime: '16:30' },
{ startTime: '19:00', endTime: '21:15' }
],
totalTime: ''
};
},
mounted() {
this.totalTimeInterval();
},
methods: {
calculateTimeDiff(startTime, endTime) {
// 获取当前日期
const currentDate = new Date().toLocaleDateString();
// 将开始时间和结束时间转换为Date对象
const startDate = new Date(`${currentDate} ${startTime}`);
const endDate = new Date(`${currentDate} ${endTime}`);
// 如果结束时间小于开始时间,则表示跨天了
if (endDate < startDate) {
endDate.setDate(endDate.getDate() + 1); // 结束日期往后推一天
}
// 计算时间差(以毫秒为单位)
const timeDiff = endDate - startDate;
// 将时间差转换为分钟
const minutes = Math.floor(timeDiff / (1000 * 60));
// 返回结果 return `${minutes}分钟`;
},
totalTimeInterval() {
let totalMinutes = 0;
for (let i = 0; i < this.array.length; i++) {
const timeObj = this.array[i];
const startTime = timeObj.startTime;
const endTime = timeObj.endTime;
const minutes = parseInt(this.calculateTimeDiff(startTime, endTime));
if (!isNaN(minutes)) {
totalMinutes += minutes;
}
}
// 将总时间间隔转换为小时和分钟
const hours = Math.floor(totalMinutes / 60);
const remainingMinutes = totalMinutes % 60;
// 更新总时间间隔
this.totalTime = `${hours}小时${remainingMinutes}分钟`;
}
}