×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Javascript
Posted by: Kenny Girard
Added: Oct 9, 2021 3:31 AM
Views: 2445
Tags: no tags
  1. public class Time1 {
  2.    private int hour; // 0 - 23  
  3.    private int minute; // 0 - 59
  4.    private int second; // 0 - 59
  5.  
  6.    // set a new time value using universal time; throw an
  7.    // exception if the hour, minute or second is invalid
  8.    public void setTime(int hour, int minute, int second) {
  9.       // validate hour, minute and second
  10.       if (hour < 0 || hour >= 24 || minute < 0 || minute >= 60 ||
  11.          second < 0 || second >= 60) {
  12.          throw new IllegalArgumentException(              
  13.             "hour, minute and/or second was out of range");
  14.       }
  15.  
  16.       this.hour = hour;
  17.       this.minute = minute;
  18.       this.second = second;
  19.    }
  20.  
  21.    // convert to String in universal-time format (HH:MM:SS)
  22.    public String toUniversalString() {
  23.       return String.format("%02d:%02d:%02d", hour, minute, second);
  24.    }
  25.  
  26.    // convert to String in standard-time format (H:MM:SS AM or PM)
  27.    public String toString() {
  28.       return String.format("%d:%02d:%02d %s",        
  29.          ((hour == 0 || hour == 12) ? 12 : hour % 12),
  30.          minute, second, (hour < 12 ? "AM" : "PM"));  
  31.    }
  32. }