Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Time
- {
- private int hour; // 0 - 23
- private int minute; // 0 - 59
- private int second; // 0 - 59
- //constructor to set the time
- public Time(int hour, int minute, int second)
- {
- //check if set time is correct
- if ((hour >= 0 && hour < 24) && ( minute >= 0 && minute < 60) && (second >= 0 && second < 60))
- {
- this.hour = hour;
- this.minute = minute;
- this.second = second;
- } else {
- this.hour = 0;
- this.minute = 0;
- this.second = 0;
- }
- }
- //to 24 hour format
- public String to24HourFormat()
- {
- return String.format ("%02d:%02d:%02d", hour, minute, second);
- }
- //to 12 hour format AM/PM
- public String to12HourFormat()
- {
- //is it am or pm
- String dayOrNight;
- if (hour < 12) {
- dayOrNight = "AM";
- } else {
- dayOrNight = "PM";
- }
- //get current hour by modulo
- if (hour == 0 || hour == 12) {
- hour = 12;
- } else {
- hour = hour % 12;
- }
- return String.format ("%d:%02d:%02d %s", hour, minute, second, dayOrNight);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement