trizehn

Time2

Oct 14th, 2020
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.76 KB | None | 0 0
  1.  
  2. /**
  3.  * Write a description of class Time2 here.
  4.  *
  5.  * @author Daffa Tristan Firdaus
  6.  * @version 0.1 8 Oktober 2020
  7.  */
  8. public class Time2
  9. {
  10.     private int hour, minute, second;
  11.    
  12.     public Time2()
  13.     {
  14.         this(0, 0, 0);
  15.     }
  16.     public Time2(int h)
  17.     {
  18.         this(h, 0, 0);
  19.     }
  20.     public Time2(int h, int m)
  21.     {
  22.         this(h, m, 0);
  23.     }
  24.     public Time2(int h, int m, int s)
  25.     {
  26.         setTime(h, m, s);
  27.     }
  28.     public Time2(Time2 time)
  29.     {
  30.         this(time.getHour(), time.getMinute(), time.getSecond());
  31.     }
  32.    
  33.     public void setTime(int h, int m, int s)
  34.     {
  35.         setHour(h);
  36.         setMinute(m);
  37.         setSecond(s);
  38.     }
  39.     public void setHour(int h)
  40.     {
  41.         if(h >= 0 && h < 24) hour = h;
  42.         else throw new IllegalArgumentException("hour must be 0-23");
  43.     }
  44.     public void setMinute(int m)
  45.     {
  46.         if(m >= 0 && m < 60) minute = m;
  47.         else throw new IllegalArgumentException("minute must be 0-59");
  48.     }
  49.     public void setSecond(int s)
  50.     {
  51.         if(s >= 0 && s < 60) second = ((s >= 0 && s < 60)? s :0);
  52.         else throw new IllegalArgumentException("second must be 0-59");
  53.     }
  54.    
  55.     public int getHour()
  56.     {
  57.         return hour;
  58.     }
  59.     public int getMinute()
  60.     {
  61.         return minute;
  62.     }
  63.     public int getSecond()
  64.     {
  65.         return second;
  66.     }
  67.    
  68.     public String toUniversalString()
  69.     {
  70.         return String.format("%02d:%02d:%02d", getHour(), getMinute(), getSecond());
  71.     }
  72.     public String toString()
  73.     {
  74.         return String.format("%d:%02d:%02d %s",
  75.         ( (getHour() == 0 || getHour() == 12) ? 12 : getHour() % 12 ),
  76.         getMinute(), getSecond(), ( getHour() < 12 ? "AM" : "PM" ));
  77.     }
  78. }
  79.  
Advertisement
Add Comment
Please, Sign In to add comment