Java Countdown timer problem

Posted on 2011-02-20
Last Modified: 2012-06-21
I am attaching some code I am using for a countdown timer.  It will not let me start a time of less than one hour.  I have tried sending it 0 hours, 2 minutes, and 27 seconds but it starts with 12 hours, 2 minutes, and 27 seconds.  Also I don't know how to stop it before it runs the time to 00:00:00.  Any Ideas.

public class CountDownTimer implements ActionListener {
    private long count;
    private int hours;
    private int minutes;
    private int seconds;
    private DateFormat df;

    public CountDownTimer(int hours, int minutes, int seconds) {
      // suppose to show as in  HR:MIN:SEC.

      Calendar cal = Calendar.getInstance();
      cal.set(Calendar.HOUR, hours);
      cal.set(Calendar.MINUTE, minutes);
      cal.set(Calendar.SECOND, seconds);
      count = cal.getTime().getTime();
      df = new SimpleDateFormat("hh:mm:ss");

      javax.swing.Timer t = new javax.swing.Timer(1000, this);

    public void actionPerformed(ActionEvent e) {
      // suppose to countdown till OO HR 00 MIN 00 SEC
        jtAudioCutsTimer.setFont(new Font("sansserif", Font.PLAIN, 36));
      count -= 1000;
Question by:sargent240
  • 4
  • 3
LVL 35

Expert Comment

ID: 34939032
It is probably not the intended use of Calendar or DateFormat but to get it to do what you want, you just have to change the format that you are passing to SimpleDateFormat. At the moment, it is printing in 12 hour format AM/PM but you should set it to 24 hour format. Just change

 df = new SimpleDateFormat("hh:mm:ss");


 df = new SimpleDateFormat("HH:mm:ss");

And to stop it you just have to call stop() on the Timer object that you created. You can do this in at least 2 ways; you can create a variable in the class to store the Timer object (at the moment, it is only in scope in the constructor so you cant use it outside that function) and then you can do whatever you want with it anywhere in the class, or you can get to the object through the ActionEvent object in the actionPerformed function with

 ((javax.swing.Timer) e.getSource()).stop();

It just depends in which function that you need to call stop()

Author Comment

ID: 34940104
Thank you very much for your reply!  I changed the hh from lower to upper case, set the hour to 0, the minutes to 2, and the seconds to 16 and the counter started with 12:02:16.  Did I miss something?
Thanks - Cheers

Author Comment

ID: 34940141
Another thought, maybe I need to take another approach.  Is there a fairly simple way to do what I am doing here.  I don't mind the way it is so if I can get it fixed great or you might have seen or been involved with some code that does what I need.  Again THANKS!
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

LVL 35

Accepted Solution

mccarl earned 500 total points
ID: 34940248
Ahh, I didn't do enough testing (or was just lucky enough to not see an additional problem). The change I made above would have working if you were testing it out while your current timezone was AM. That's why it worked fine for me this morning when I tried it out. I just tried it again and it went back to 12 instead of 0. The problem is that I am now in PM too.

To fix that problem, you have to make 1 additional change, from ...

 cal.set(Calendar.HOUR, hours);


 cal.set(Calendar.HOUR_OF_DAY, hours);

As to your second post, I would probably suggest that you do take another approach. Which approach that is depends on info that only you know, such as exactly how this is going to be used, etc. The problem with the above is that you are using a Calendar/DateFormat object to represent a duration of time, but it is not really meant for that. It is meant to be able to specify a point in time.

As an example of where this may present an issue for you, it may not do what you expect it to do on the daylight savings changeover days. What is happening is that Calendar.getInstance() is getting you a calendar that is set to the current date and time, and then you are just setting the time to be eg. 2 miinutes and 16 seconds past midnight, and then you are making it just print out the time part of that. On the DLS days if someone entered a timer duration of 5 hours, the timer would expire either 4 or 6 hours later, depending on which DLS day it is.

Unfortunately the standard Java libraries have nothing to support durations of time the way you want to use it. So I can see 2 alternatives, if you will only ever have timer durations in hours, minutes & seconds then it may be easier to just do everything manually, ie. count = ((hours * 60 + minutes) * 60 + seconds) * 1000; and then manually convert that back to fields and manually format the string. Or if now (or down the track) you will want to properly support durations of days, months, etc, I would look into a library called Joda Time ( that can handle those type of things properly, including formatting not just date/times but periods and durations, etc.

Author Comment

ID: 34940349
Great.  I was messing around while waiting to hear from you,I changed Hours to Hours_Of_Day and it started to work.  Thank you for the narration on the calendar class, it is great info and and will go into my three ring binder.  I am writing some code to automate my radio station.  The timer is used to count down the audio cut that is playing.  To date we have not had a cut that has lasted more that 7 or 8 minutes.  It may come to a time when we would play a cut that would last an hour or two but that is it.  It is only used so the man in the control room knows whether he has enough time to go to the men's room or not.  I think this will work fine.  I have only one other problem and that is when it comes to 00:00:00 I would like it to stop, not turn over to 23:00:00 and start down.  If I can solve that problem I would use the code until I needed to change it but if stopping at 00:00:00 is a problem I will recode it.  Any thoughts?
LVL 35

Expert Comment

ID: 34940375
In this case the easiest (but not necessarily the best) way to do it would probably be to just look for the string being equal to "00:00:00", so you would have something like...

            ((javax.swing.Timer) e.getSource).stop();
      count -= 1000;

But I am not sure if you will need to clean up else, notify some other part of the code that the timer has stopped, etc. It is a bit hard to say without seeing a bigger picture of the code.

(Note: the nicer ways to do this would be if you did go for 1 of the 2 alternatives that I mentioned above. It would then look a bit more like... if(count <= 0) .......)

Author Closing Comment

ID: 34940386
The best yet

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
groupNoAdj 7 105
Eclipse Neon start with Admin account only 6 143
control image tags in a string ? 12 142
ejb message driven bean mdb creation steps 2 22
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Does the idea of dealing with bits scare or confuse you? Does it seem like a waste of time in an age where we all have terabytes of storage? If so, you're missing out on one of the core tools in every professional programmer's toolbox. Learn how to …
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

856 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question