Advertisement
Dr_U

Time2

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