Is there a convenient way of subtracting different units of time using the Calendar class? I am making a timer that counts down for multiple hours and prints the time to the console in hours, minutes, and seconds. I don't want to use any libraries such as Joda Time in this program. I also want to use the Calendar class, and not the Date class, unless it is too difficult.
This is my current code and it only prints the remaining time in seconds:
import java.awt.*;
import java.util.*;
public class ClickWhen {
public static void main(String[] args) throws AWTException {
int minGoal = 30;
int hourGoal = 6+12;
Calendar time = Calendar.getInstance();
int minute = time.get(Calendar.MINUTE);
int hour = time.get(Calendar.HOUR_OF_DAY);
int second = time.get(Calendar.SECOND);
int sRemaining = (minGoal*60+hourGoal*3600)-(second+minute*60+hour*3600);
boolean isGoing = true;
Robot r = new Robot();
while(isGoing) {
r.delay(1000);
time = Calendar.getInstance();
minute = time.get(Calendar.MINUTE);
hour = time.get(Calendar.HOUR_OF_DAY);
second = time.get(Calendar.SECOND);
if(hour >= hourGoal && minute >= minGoal) {
// do something
isGoing = false;
}
if(hour >= 12) {
System.out.println(hour-12+":"+minute+":"+second+" P.M.");
}
if(hour < 12) {
System.out.println(hour+":"+minute+":"+second+" A.M.");
}
sRemaining--;
System.out.println("Seconds Remaining: "+sRemaining);
}
}
}
This is my first question on Stack Overflow, so how did I do?