如何限制时间选项确切的小时值,应该限制后的时间经过



我只需要时间选项11 AM to 1 PM (1:00:00 PM only),如果系统时间是1:00:01 PM也不应该被允许。如果时间在1 PM之后流逝,我需要将选项可用性设置为false。从现在到1:59:59 PM,我得到的价值是真的。如果我的系统时间移动到2 PM,只会变为false。建议我如何获得解决方案。我应该只允许1:00:00 PM,不应该允许任何其他选项。

public timeOptions = ['11 AM', '12 PM', '1 PM'];
private currentTime: string[] = new Date()
.toLocaleTimeString('en-US')
.split(' ');
private formattedTime: string = `${this.currentTime[0].split(':')[0]} ${
this.currentTime[1]
}`;
private timeIndexOnOptions: number = this.timeOptions.indexOf(
this.formattedTime
);

public timeOptionAvaialable(): void {
let isOptionAvailable = this.timeIndexOnOptions != -1 ? true : false;
console.log(isOptionAvailable);

Stacklitz

这里有一些代码

const timeOptions = ['11 AM', '12 PM', '1 PM'];
const today = new Date().toLocaleTimeString('en-US').split(' ')
const timeSplit = today[0].split(':')
const index = timeOptions.indexOf(timeSplit[0] + ' ' + today[1])
// it will not wait for 1:00:00 it return false when 12:59:59 hit
if (index > -1 && index !== (timeOptions.length - 1)) {
console.log(true);
} else {
console.log(false);
}

看起来您想要决定currentTime是否在一个区间中。那么,我可以建议另一种方法吗?创建表示间隔开始的日期对象和表示间隔结束的日期对象,并检查当前时间是否在该间隔中。

const startHours = 11;
const endHours = 13;
// create a Date object for 11 AM today
const startTime = new Date();
startTime.setHours(startHours, 0, 0, 0);
// create a Date object for 1 PM today
const endTime = new Date();
endTime.setHours(endHours, 0, 0, 0);
// check if current time is in the interval
const currentTime = new Date();
const isOptionAvailable = currentTime > startTime && currentTime < endTime

最新更新