Advertisement
Dr_U

TimeFormat

Oct 8th, 2020
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.18 KB | None | 0 0
  1.  
  2. // flg 8.1 time1.java
  3. // time1 class declaration maintains the time in 24 hour format
  4.  
  5. public class Time1
  6. {
  7.     private int hour;
  8.     private int minute;
  9.     private int second;
  10.    
  11.     //set a new time value using universal time;
  12.     //throw an exception if the hour, minutes, second is invalid
  13.     public void setTime(int h, int m, int s)
  14.     {
  15.         // validate hour,minute, second
  16.         if((h >= 0 && h< 24 ) && (m >= 0 && h< 60 ) && (s >= 0 && h< 60 ))
  17.         {
  18.             hour = h;
  19.             minute = m;
  20.             second = s;
  21.         }
  22.         else
  23.        
  24.             throw new IllegalArgumentException(
  25.                 "hour, minute, second and/or was out of range");
  26.         }// end of methods  
  27.        
  28.     // convert to string in universal-time format (HH:MM:SS)
  29.     public String toUniversalString()
  30.     {
  31.         return String.format("%02d:%02d:%02d",hour,minute,second);
  32.     }
  33.     // convert to string in Standard-time format (HH:MM:SS AM or PM)
  34.     public String toString()
  35.     {
  36.         return String.format("%d:%02d:%02d %s",
  37.         ((hour == 0 || hour == 12) ? 12 : hour % 12),
  38.         minute, second,(hour <12 ? "AM" : "PM"));
  39.     }
  40. }
  41.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement