check if time in range between 12:00 am to 6:59 am

Issue

I using angular and ionic 4. I got issue to checking time range between 12:00 am to 6:59 am.

Example code as below

HTML

<ion-datetime[(ngModel)]="data.laterTime"
           (ionChange)="saveDate($event)" displayFormat="HH:mm" min="00:00"
           max="23:59" hourValues="00,01,02,03,04,05,06,07,08,09,10,11,12,13,14,15,16,17,18,19,20,21,22,23" minuteValues="0, 15, 30, 45"> </ion-datetime>

ts

saveDate($event) {

    if (moment($event.detail?.value).format('hh:mm a') <= '12:00 am' && moment($event.detail?.value).format('hh:mm a') < '07:00 am') {
       console.log("success!!!");
    }
}

Solution

You just need to convert each time strings to moment and compare it. Like this:

wrapIntoMoment(value: string) {
    return moment(value, 'h:mma');
  }

saveDate($event) {
  if (
    this.wrapIntoMoment($event.detail?.value) >=
      this.wrapIntoMoment('12:00 am') &&
    this.wrapIntoMoment($event.detail?.value) <
      this.wrapIntoMoment('06:59 am')
  ) {
    console.log('success!!!');
  }
}

There is an example for you with some test cases in constructor:
Example

Answered By – Yan Koshelev

Answer Checked By – Terry (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.