Home > Enterprise >  How to limit the hours between 0 to 12, please?
How to limit the hours between 0 to 12, please?

Time:09-04

Let's say it's 4 p.m, In my console, I display 16 hours (PM) instead of 4 hours (PM).

enter image description here

How to limit the hours between 0 to 12, please?

export class HomeComponent implements OnInit {

  today: Date = new Date();
  
  hours: number = 0;
  minutes: number = 0;
  seconds: number = 0;

  flag: boolean = false; 
  day_night: string = "";

 
  constructor() {}

  ngOnInit(): void {

    this.hours = 16;     //this.today.getHours();
    this.minutes = 40;   //this.today.getMinutes();
    this.seconds = 20;   //this.today.getSeconds();

    if (this.flag) {
      this.hours >= 12;
      this.day_night = "AM";     
    } else {
      this.day_night = "PM";    
    }

    console.log("It's "   this.hours   " hours, "   this.minutes   " minutes and "   this.seconds   " seconds.");
    console.log("Time of day => "   this.day_night);
    
  }

}

CodePudding user response:

It is really simple.

After 12 it should circle back from 1 and then so on

You can use that by using modulus operator

You can achieve this by modifying the if statement like this

ngOnInit(): void {

    this.hours = 16;     //this.today.getHours();
    this.minutes = 40;   //this.today.getMinutes();
    this.seconds = 20;   //this.today.getSeconds();

    // If hours is greater then 12, it is PM, else it is AM
    if (this.hours > 12) {
      this.hours = this.hours % 12; // This will limit the value of hours under 12
      this.day_night = "PM";     
    } else {
      this.day_night = "AM";    
    }

    console.log("It's "   this.hours   " hours, "   this.minutes   " minutes and "   this.seconds   " seconds.");
    console.log("Time of day => "   this.day_night);
    
  }
  • Related