Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

}

>Solution :

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);
    
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading