将日期舍入到最接近的 5 分钟时刻作为数组
Round date to the nearest 5 minutes moment as array
我需要使用 Date() utc 将时间四舍五入到最接近的五分钟,然后将其作为数组推送
示例:
[
"2019_10_9_00_05",
"2019_10_9_00_10",
"2019_10_9_00_15",
"2019_10_9_00_20",
]
代码
const now = moment();
const time= [];
for (let i = 0; i < 4; i++) {
now.add(5, 'minutes');
time.push(now.utcOffset(-1).format('YYYY_M_DD_HH_mm'));
}
console.log(time);
输出
[
"2019_10_9_00_03",
"2019_10_9_00_7",
"2019_10_9_00_11",
"2019_10_9_00_16",
]
请有任何解决方案
您需要先检查分钟值是否是 5 的倍数。
const now = moment();
const factor = 5;
const time = [];
const minutes = now.minutes();
if (minutes !== 0 && minutes % factor) { // Check if there is a remainder
const remainder = minutes % factor; // Get remainder
now.add(factor - remainder, 'minutes'); // Update minutes value to nearest 5
}
for (let i = 0; i < 4; i++) {
time.push(now.utcOffset(-1).format('YYYY_M_DD_HH_mm'));
now.add(5, 'minutes');
}
console.log(time);
结果:
now: 2019_10_11_09_19
["2019_10_10_21_20", "2019_10_10_21_25", "2019_10_10_21_30", "2019_10_10_21_35"]
我需要使用 Date() utc 将时间四舍五入到最接近的五分钟,然后将其作为数组推送
示例:
[
"2019_10_9_00_05",
"2019_10_9_00_10",
"2019_10_9_00_15",
"2019_10_9_00_20",
]
代码
const now = moment();
const time= [];
for (let i = 0; i < 4; i++) {
now.add(5, 'minutes');
time.push(now.utcOffset(-1).format('YYYY_M_DD_HH_mm'));
}
console.log(time);
输出
[
"2019_10_9_00_03",
"2019_10_9_00_7",
"2019_10_9_00_11",
"2019_10_9_00_16",
]
请有任何解决方案
您需要先检查分钟值是否是 5 的倍数。
const now = moment();
const factor = 5;
const time = [];
const minutes = now.minutes();
if (minutes !== 0 && minutes % factor) { // Check if there is a remainder
const remainder = minutes % factor; // Get remainder
now.add(factor - remainder, 'minutes'); // Update minutes value to nearest 5
}
for (let i = 0; i < 4; i++) {
time.push(now.utcOffset(-1).format('YYYY_M_DD_HH_mm'));
now.add(5, 'minutes');
}
console.log(time);
结果:
now: 2019_10_11_09_19
["2019_10_10_21_20", "2019_10_10_21_25", "2019_10_10_21_30", "2019_10_10_21_35"]