[英]How to group timelines by hrs
可以說我有一個JSON數據數組,其日期格式為timeStarted和timeEnded。 我正在努力將timeSept花費幾個小時。 例如,
[{timeStarted: '00:10:30', timeEnded: '00:14:02'},
{timeStarted: '00:48:08', timeEnded: '02:33:33'}, ...]
我試圖將它們分組,所以我得到數組像
[{hrs: '0', timeSpent: '16'},
{hrs: '1', timeSpent: '60'},
{hrs: '2', timeSpent: '34'}, ...]
我曾嘗試過數十億次來對它們進行分組,但我不知道該怎么做:我總是每小時獲得95分鍾之類的值。 至少我需要一種正確的思考方式。 謝謝。
根據timeSpent和第一個數組的值,您似乎想獲得一個數組 , 該數組表示每個時鍾小時(例如,從9:00到10:00或14:00到15:00)是多少?花了” 。
如果是這樣的話,您可以通過獲取每個間隔的小時和分鍾(甚至是秒數,如果要細化),並計算每個小時增加了多少分鍾來做到這一點。
對於間隔在一個時鍾小時內的簡單情況,可以通過從開始時間中減去結束時間來實現。 在一個小時的時間間隔中,情況會稍微復雜一些。 請參閱下面的代碼,了解一種可以解決此問題的方法。 可能有更好的方法,並且代碼只寫到最后一刻,但這只是一個開始。
以下hours
數組的鍵對應於每個時鍾小時。
const timesElapsed = [
{timeStarted: '00:10:30', timeEnded: '00:14:02'},
{timeStarted: '00:48:08', timeEnded: '02:33:33'}
]
// Initialize hours array: each key of the array represents a specific clock hour
let hours = []
for (let interval of timesElapsed) {
// Get the pertinent data as Numbers
const startHour = (Number)(interval.timeStarted.split(':')[0])
const startMinute = (Number)(interval.timeStarted.split(':')[1])
const endHour = (Number)(interval.timeEnded.split(':')[0])
const endMinute = (Number)(interval.timeEnded.split(':')[1])
// Initialize elements in Hour array if need be
if (hours[startHour] === undefined) hours[startHour] = 0
if (hours[endHour] === undefined) hours[endHour] = 0
// An interval within an hour
if (startHour === endHour) {
hours[startHour] += (endMinute - startMinute)
} else {
// The first hour of a multi-hour interval
hours[startHour] += 60 - startMinute
// The middle hours, if any
for (let i = startHour + 1; i < endHour; i++)
hours[i] = 60
// The final hour
hours[endHour] += endMinute
}
}
// console.log(hours)
// [16, 60, 33]
如果您的時間始終是格式為hh:mm:ss
字符串,則可以使用一些數學運算拆分一個簡單的字符串:
const times = [
{ timeStarted: '00:10:30', timeEnded: '00:14:02' },
{ timeStarted: '00:48:08', timeEnded: '02:33:33' },
];
const withHours = times.map(time => {
// Split on colon to get the components of the timestamp
var start = time.timeStarted.split(':');
var end = time.timeEnded.split(':');
// Convert to seconds by multiplying each component by how many seconds it's worth
var startSeconds = (+start[0]) * 60 * 60 + (+start[1]) * 60 + (+start[2]);
var endSeconds = (+end[0]) * 60 * 60 + (+end[1]) * 60 + (+end[2]);
// Find the difference in seconds and convert back to hours
// We'll also floor this cause it looks like you want ints rounded down
var hrs = Math.floor((endSeconds - startSeconds) / (60 * 60));
return {
timeStarted: time.timeStarted,
timeEnded: time.timeEnded,
hrs,
};
});
編輯
只是注意到您在那里還有一個名為timeSpent
的附加字段。 不知道那應該是什么。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.