Expiring Today—Celebrate National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17


Java Countdown timer problem

Posted on 2011-02-20
Medium Priority
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
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
LVL 36

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!
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

LVL 36

Accepted Solution

mccarl earned 2000 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 (http://joda-time.sourceforge.net/index.html) 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 36

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

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

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

Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
This article will show how Aten was able to supply easy management and control for Artear's video walls and wide range display configurations of their newsroom.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

730 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