Take input hours mins secs from user and start a countdown in hh:mm:ss format

584 views Asked by At

I am facing problem in starting timer and how to place data into date.

This is my code:

Calendar cl = Calendar.getInstance();
cl.set(Calendar.HOUR, 0);
cl.set(Calendar.MINUTE, 0);
cl.set(Calendar.SECOND, 0);
cl.add(Calendar.HOUR, hr);
cl.add(Calendar.MINUTE, min);
cl.add(Calendar.SECOND, sec);
Date date = cl.getTime();
Timer t =new Timer(1000, new ActionListener() {
  @Override
  public void actionPerformed(ActionEvent ae) {
     SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
     jLabel2.setText(timeFormat.format(date));
  }
});
t.start();

Is it correct to use Calendar to place data in date and start timer?

1

There are 1 answers

4
Anonymous On

I don’t think you should use a Calendar for this. A Calendar is meant for representing a point in calendar time, not a duration in hours, minutes and seconds. Also, Calendar is old stuff now and replaced by new and more programmer friendly classes in Java 8 (see the java.time package).

I understand from the comments that you want a count-down timer. I suggest:

    Timer t = new Timer(1000, new ActionListener() {
        Duration time = Duration.ofHours(hr).plusMinutes(min).plusSeconds(sec);
        @Override
        public void actionPerformed(ActionEvent ae) {
            time = time.minusSeconds(1);
            jLabel2.setText(formatDuration(time));
        }
    });
    t.start();

I am using the Duration class, one of the classes introduced in Java 8. It is designed for a duration in hours, minutes and seconds, so this is what we need for the job. It doesn’t lend itself well to formatting, though. You may use its toString method, it will give you a string like PT9M52S for 9 minutes 52 seconds, probably not what most users find most intuituve. Instead I am using this auxiliary method for formatting:

static String formatDuration(Duration dur) {
    long hr = dur.toHours();
    Duration remainder = dur.minusHours(hr);
    long min = remainder.toMinutes();
    long sec = remainder.minusMinutes(min).getSeconds();
    return String.format("%02d:%02d:%02d", hr, min, sec);
}