Home > Blockchain >  How to restrict time options exact hour value, should be restrict after the time passed
How to restrict time options exact hour value, should be restrict after the time passed

Time:06-19

I need time options only 11 AM to 1 PM (1:00:00 PM only) and If system time is 1:00:01 PM also should not be allowed. if time passed after 1 PM I need to get the option availability as false.As of now till 1:59:59 PM I'm getting value as true. If my system time moved to 2 PM only getting false. Suggest me how to get the solution for this. I should allow only 1:00:00 PM and should not be allowed any other options.

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);

Stackblitz

CodePudding user response:

here is some piece of code

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);
}

CodePudding user response:

It look like you want to decide if currentTime is in an interval. May I then suggest an alternate approach? Create a date object that represents the beginning of the interval and a date object that represents the end of the interval and check whether current time is in that interval.

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
  • Related