You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中如何计算HH:MM格式出发时间的平均值?

平均出发时间计算实现方案

已知前提

你的对象属性定义如下:

numberOfReturns: number = 0;
returns_explanations: string [] = [];
departure_time: string = '';
arrival_time: string = '';

其中departure_time为HH:MM格式的时间字符串,示例值如下:

departure_time: 08:15
departure_time: 08:02
departure_time: 09:00

原代码错误原因

  1. 初始average为null,首次调用moment(null)会返回当前时间,而非初始0值,累加逻辑从根上错误
  2. moment.add()方法不支持直接传入完整moment对象作为参数,需要指定累加的数值和单位
  3. 直接将Date对象除以数组长度,属于语法逻辑错误,无法得到预期的时间平均值

正确实现

原生JS实现(无需第三方依赖)

// 边界判断:数组为空时直接返回空或者自定义默认值
if (!workAccountItem.length) {
  console.log('数组为空,无法计算平均值');
  return '';
}

let totalMinutes = 0;
const count = workAccountItem.length;

// 累加所有时间对应的总分钟数
workAccountItem.forEach(item => {
  const [hour, minute] = item.departure_time.split(':').map(Number);
  totalMinutes += hour * 60 + minute;
});

// 计算平均分钟数,可根据业务需求调整取整规则
const avgMinutes = Math.round(totalMinutes / count);

// 转换为HH:MM格式,不足两位补前导0
const avgHour = String(Math.floor(avgMinutes / 60)).padStart(2, '0');
const avgMinute = String(avgMinutes % 60).padStart(2, '0');
const averageDepartureTime = `${avgHour}:${avgMinute}`;

Moment.js实现

import moment from 'moment';

if (!workAccountItem.length) {
  console.log('数组为空,无法计算平均值');
  return '';
}

let totalMinutes = 0;
const count = workAccountItem.length;

workAccountItem.forEach(item => {
  const time = moment(item.departure_time, 'HH:mm');
  totalMinutes += time.hours() * 60 + time.minutes();
});

const avgMinutes = Math.round(totalMinutes / count);
const averageDepartureTime = moment()
  .startOf('day')
  .add(avgMinutes, 'minutes')
  .format('HH:mm');

补充说明

如果需要处理跨天场景(比如存在23:00和01:00的时间,需要判断是算当天还是次日的平均),需要额外增加业务逻辑判断,上述方案默认所有时间都属于同一天的00:00-23:59区间。

内容的提问来源于stack exchange,提问作者erhhhh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 12:45:06