让我们说我有日期格式为timeStarted和timeEnded的JSON数据数组。我正在努力将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分钟之类的值。至少我需要一种正确的思考方式。谢谢。
答案 0 :(得分:3)
根据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]
答案 1 :(得分:1)
如果您的时间始终是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
的附加字段。不知道那应该是什么。