如何计算数组对象中各事件的总时长?
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:
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); }
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);
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' }
- If
start_datetime/end_datetimeare missing for some events, you can fall back tostartTime/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
YYYYMMDDMHHmmorHHmmformat; adjust the helper function if your data has variations (e.g., single-digit months/days).
内容的提问来源于stack exchange,提问作者user21

