-3

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?

shifu
  • 672
  • 8
  • 37

1 Answers1

3

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);
}
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • actually i want to place this hr min sec data in a label where countdown start with help timer !!! help me doing it – priyanka madishetty Apr 01 '17 at 08:14
  • Alright. Do you mean, the label should show the entered values first, and every second count 1 second down? – Ole V.V. Apr 01 '17 at 08:16
  • 2
    Because of the ability for the timer to lose time, I'd calculate the actual duration that the timer has been ticking since it was started – MadProgrammer Apr 01 '17 at 10:23
  • Nice idea, @MadProgrammer. Whether it’s worth it depends on the accuracy requirements. You may for example use `Duration.between(startTime, Instant.now())` where `startTime` is the `Instant` when the timer was started. Maybe easier, once calculate the instant when the timer should reach 0 and then use `Duration.between(Instant.now(), endTime)`. – Ole V.V. Apr 01 '17 at 10:26