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

如何计算数组对象中各事件的总时长?

Alright, let's break down how to calculate the total duration for each event in your array. Based on the data structure you provided, here's a practical, step-by-step solution using JavaScript:

1. First, Parse Time Strings into Calculable Values

Your datetime format is YYYYMMDDMHHmm (e.g., 20180509M2300), and you also have HHmm-formatted startTime/endTime. We’ll prioritize start_datetime and end_datetime because they include dates—critical for handling cross-day events (like your first "Sleep" event that runs from 2018-05-09 23:00 to 2018-05-10 01:00; using just HHmm would give an incorrect negative duration).

Here’s a helper function to convert the datetime string into total minutes since epoch (easy for duration calculations):

function parseDatetimeToMinutes(datetimeStr) {
  // Split string into date and time parts: "20180509M2300" → ["20180509", "2300"]
  const [datePart, timePart] = datetimeStr.split('M');
  
  // Extract year, month (0-indexed for Date object), day
  const year = parseInt(datePart.slice(0, 4), 10);
  const month = parseInt(datePart.slice(4, 6), 10) - 1;
  const day = parseInt(datePart.slice(6, 8), 10);
  
  // Extract hour and minute
  const hour = parseInt(timePart.slice(0, 2), 10);
  const minute = parseInt(timePart.slice(2, 4), 10);
  
  // Convert to total minutes
  const date = new Date(year, month, day, hour, minute);
  return date.getTime() / (1000 * 60);
}
2. Group Events by Name & Calculate Total Duration

We’ll use an object to track cumulative durations for each event. Loop through every item in your array, compute the single event’s duration, then add it to the corresponding event’s total:

// Your sample array (add more events as needed)
const arr = [
  { "startTime": "1300", "endTime": "1700", "eventName": "Sleep", "end_datetime": "20180510M0100", "start_datetime": "20180509M2300" },
  { "startTime": "0800", "endTime": "1200", "eventName": "Breakfast", "end_datetime": "20180507M1200", "start_datetime": "20180507M0800" },
  { "startTime": "1300", "endTime": "1400", "eventName": "Lesson", "end_datetime": "20180507M1400", "start_datetime": "20180507M1300" }
];

// Object to store total duration (in minutes) per event
const eventTotalDurations = {};

arr.forEach(event => {
  const startMins = parseDatetimeToMinutes(event.start_datetime);
  const endMins = parseDatetimeToMinutes(event.end_datetime);
  const singleDuration = endMins - startMins;

  // Update total duration for the event
  if (eventTotalDurations[event.eventName]) {
    eventTotalDurations[event.eventName] += singleDuration;
  } else {
    eventTotalDurations[event.eventName] = singleDuration;
  }
});

// Optional: Format minutes into readable "Xh Ym" format
const formattedDurations = Object.entries(eventTotalDurations).reduce((acc, [eventName, totalMins]) => {
  const hours = Math.floor(totalMins / 60);
  const remainingMins = totalMins % 60;
  acc[eventName] = `${hours}h ${remainingMins}m`;
  return acc;
}, {});

// Log results
console.log('Total durations (minutes):', eventTotalDurations);
console.log('Formatted total durations:', formattedDurations);
3. Sample Output

For your provided 3 events, you’ll get:

Total durations (minutes): { Sleep: 120, Breakfast: 240, Lesson: 60 }
Formatted total durations: { Sleep: '2h 0m', Breakfast: '4h 0m', Lesson: '1h 0m' }
Key Notes
  • If start_datetime/end_datetime are missing for some events, you can fall back to startTime/endTime—but be aware this won’t handle cross-day events. You’d need to add extra logic to check if end time is earlier than start time (indicating a next-day event).
  • Ensure all time strings follow the exact YYYYMMDDMHHmm or HHmm format; adjust the helper function if your data has variations (e.g., single-digit months/days).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:07:50