0

I want to add a clock to my application. I get the unixtime from the web through json, but if I ask for it every second, after a while it declines the answer. So now I want to get the unixtime only once, when I start the application, then increase the long value by one, every second and display that.

 private void setDateLabel() throws IOException, JSONException {
        long unixtime = Unixtime.getTime();

        Timeline clock = new Timeline(new KeyFrame(Duration.ZERO, e -> {
            try {

                Date date = new Date(unixtime * 1000L);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String formatDate = sdf.format(date);
                dateLabel.setText(formatDate);
                unixtime++;
            } catch (Exception ex) {
                Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
            }
        }), new KeyFrame(Duration.seconds(1)));
        clock.setCycleCount(Animation.INDEFINITE);
        clock.play();
}

I have this, but it is not working.

The Unixtime.getTime() does not do anything else than giving back a long number.

  • Look [here](https://stackoverflow.com/questions/54769610/how-can-i-monitor-the-duration-of-printing-in-text-java-fx/54770661#54770661) at how the `AtomicInteger` works. – SedJ601 Feb 26 '19 at 00:32

1 Answers1

0

I am not sure if I understand your requirment, you want to get the time only once and then keep updating it locally. right? I would try to use AtomicLong for this purpose. Something like..

Just a side note: You can create only one instance of SimpleDateFormat rather than creating a new one every second.

private void setDateLabel() throws IOException, JSONException {
        AtomicLong unixtime = new AtomicLong(Unixtime.getTime());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Timeline clock = new Timeline(new KeyFrame(Duration.ZERO, e -> {
            try {
                Date date = new Date(unixtime.getAndIncrement() * 1000L);
                dateLabel.setText(sdf.format(date));
            } catch (Exception ex) {
                Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
            }
        }), new KeyFrame(Duration.seconds(1)));
        clock.setCycleCount(Animation.INDEFINITE);
        clock.play();
}
Sai Dandem
  • 8,229
  • 11
  • 26