4 回答
TA贡献1803条经验 获得超6个赞
假设数组总是有序的,首先是今天的时间,然后是午夜后的时间:
const orari = [
'10:00:00',
'11:00:00',
'12:00:00',
'15:00:00',
'16:00:00',
'16:30:00',
'00:00:00',
'01:00:00',
'02:00:00',
'02:30:00',
]
const currentTime = new Date().toString().match(/\d{2}:\d{2}:\d{2}/)[0]
const cutoffIndex = orari.findIndex((hour, idx) =>
hour.localeCompare(currentTime) > 0
|| (idx && hour.localeCompare(orari[idx - 1]) < 0))
// second condition required in case array contains
// _only_ times before now on same day + times after midnight
const filtered = orari.slice(cutoffIndex)
console.log(`Times after ${currentTime} -`, filtered)
TA贡献1829条经验 获得超7个赞
let curDate = new Date()
let curHour = 16//curDate.getHours()
let curMin = 30//curDate.getMinutes()
const hours=["10:00:00","11:00:00","12:00:00","16:00:00","16:30:00","00:00:00","01:00:00","02:00:00","02:30:00"];
let sliceIdx = null
hours.forEach((time, idx) => {
let hour = parseInt(time.split(':')[0])
let min = parseInt(time.split(':')[1])
if (hour == curHour && min >= curMin || hour > curHour) {
sliceIdx = sliceIdx === null ? idx : sliceIdx
}
})
let newHours = hours.slice(sliceIdx + 1)
console.log(newHours)
TA贡献1934条经验 获得超2个赞
let array = ['10:00:00', '11:00:00', '12:00:00', '16:00:00', '16:30:00', '00:00:00', '01:00:00', '02:00:00', '02:30:00' ];
let newArray = a.slice(a.indexOf('16:00:00') + 1, a.length);
如果您需要检查数组中是否存在时间,您可以将 indexOf 的值保存在另一个变量中(如果不存在则返回 -1);
TA贡献1853条经验 获得超6个赞
因为没有办法用我当前的时间数组来实现我正在寻找的东西,而且正如@lionel-rowe 提到的,我无法区分“今天早上 5 点”和“明天午夜后 5 点”,我不得不更改我的日期在我的数据库中从时间输入字符串,这样我就可以通过这种方式在一个数组中添加第二天的所有夜间时间和同一天的早上时间:
如果时间是5AM我在 DB 中设置它,'05:00:00'在 JS 中我将它设置为它的日期,而用户想在午夜后插入 5AM,我'29:00:00'在 JS 中设置小时我只是检查小时是否是>= 24那么如果条件是true我将小时设置为day + 1.
所以代码看起来类似于:
const ore = ["01:00:00", "08:30:00", "12:00:00", "12:30:00", "13:00:00", "13:30:00", "14:00:00", "14:30:00", "24:00:00", "25:00:00", "26:00:00"];
const giorno = new Date();
const final = ore.map((o) => {
const hour = o.split(':')[0];
const min = o.split(':')[1];
const date = new Date(giorno);
if (Number(hour) >= 24) {
date.setDate(date.getDate() + 1);
date.setHours(Number(hour) - 24, Number(min), 0, 0);
} else {
date.setHours(Number(hour), Number(min), 0, 0);
}
return date;
})
.sort((a, b) => a.valueOf() - b.valueOf());
console.log(final.toLocaleString());
添加回答
举报