Advertisement
zenados

Time

Sep 11th, 2019
260
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.23 KB | None | 0 0
  1. public class Time
  2. {
  3.     private int hour; // 0 - 23
  4.     private int minute; // 0 - 59
  5.     private int second; // 0 - 59
  6.  
  7.     //constructor to set the time
  8.     public Time(int hour, int minute, int second)
  9.     {
  10.         //check if set time is correct
  11.         if ((hour >= 0 && hour < 24) && ( minute >= 0 && minute < 60) && (second >= 0 && second < 60))
  12.         {
  13.             this.hour = hour;
  14.             this.minute = minute;
  15.             this.second = second;
  16.         } else {
  17.             this.hour = 0;
  18.             this.minute = 0;
  19.             this.second = 0;
  20.         }
  21.     }
  22.     //to 24 hour format
  23.     public String to24HourFormat()
  24.     {
  25.         return String.format ("%02d:%02d:%02d", hour, minute, second);
  26.     }
  27.    
  28.     //to 12 hour format AM/PM
  29.     public String to12HourFormat()
  30.     {
  31.         //is it am or pm
  32.         String dayOrNight;
  33.         if (hour < 12) {
  34.             dayOrNight = "AM";
  35.         } else {
  36.             dayOrNight = "PM";
  37.         }
  38.         //get current hour by modulo
  39.         if (hour == 0 || hour == 12) {
  40.             hour = 12;
  41.         } else {
  42.             hour = hour % 12;
  43.         }
  44.         return String.format ("%d:%02d:%02d %s", hour, minute, second, dayOrNight);
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement