I have a scenario where I need to display time slots at 30-minute intervals using Mat Select.
export const TIME=["12:00 AM","12:30 AM","01:00 AM","01:30 AM","02:00 AM","02:30 AM","03:00 AM","03:30 AM","04:00 AM","04:30 AM","05:00 AM","05:30 AM","06:00 AM","06:30 AM","07:00 AM","07:30 AM","08:00 AM","08:30 AM","09:00 AM","09:30 AM","10:00 AM","10:30 AM","11:00 AM","11:30 AM","12:00 PM","12:30 PM","01:00 PM","01:30 PM","02:00 PM","02:30 PM","03:00 PM","03:30 PM","04:00 PM","04:30 PM","05:00 PM","05:30 PM","06:00 PM","06:30 PM","07:00 PM","07:30 PM","08:00 PM","08:30 PM","09:00 PM","09:30 PM","10:00 PM","10:30 PM","11:00 PM","11:30 PM"];
My goal now is to disable all past time slots starting from the current time + 2 hours.
This is the code snippet I am working with:
<mat-select class="form-control" formControlName="pickupTime" placeholder="Select Time">
<mat-option *ngFor="let time of times" [value]="time">
{{time}}
</mat-option>
</mat-select>
isDisableTime(selectedTime: string): boolean {
if (moment(this.oneWayFormGroup.get('pickupDate').value).isSame(Date.now(), 'day')) {
let isTimeOver = false;
let currentHour = new Date().getHours() + 2;
let currentMin = new Date().getMinutes();
let currentAmPm = currentHour >= 12 ? 'PM' : 'AM';
currentHour = currentHour % 12;
let selectedHour = +selectedTime.substr(0, 2) % 12;
let selectedMin = +selectedTime.substr(3, 2);
let selectedAM_PM = selectedTime.substr(6, 2);
if (currentAmPm === selectedAM_PM) {
if (selectedHour < currentHour) {
isTimeOver = true;
} else if (selectedHour === currentHour) {
if (selectedMin < currentMin) {
isTimeOver = true;
}
}
} else {
isTimeOver = currentAmPm > selectedAM_PM;
}
return isTimeOver;
} else {
return false
}
}
The problem arises when the current time reaches 11 PM as all the preceding AM time slots get disabled.
You can refer to the StackBlitz link provided below for further clarification: