1

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?

Captain_D1
  • 61
  • 4

1 Answers1

1

If I understand your question then you could pass a negative value as the second argument to Calendar.add(int field, int value) like

int amount = -10;
cal.add(Calendar.MILLISECOND, amount);

to subtract 10 milliseconds from the Calendar cal.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • Thanks! This should work. I can clarify what I wanted I think. What I wanted was a way if I subtracted a second so that it is less then one, it would instead be set to 59 and subtract a minute, so it would work like a real clock. What I wanted was a method that did that. – Captain_D1 Nov 24 '14 at 14:33
  • @captain try the code above (it does that already). Well, a minute is sixty seconds but it does work like a clock. – Elliott Frisch Nov 24 '14 at 14:44