Formatting local time in java

Daniel Piskorz picture Daniel Piskorz · Jun 22, 2017 · Viewed 33.4k times · Source

I'm creating my JavaFX application and I need to use time label every time new list cell is created. I need to put the string with current time in HH:MM format directly into Label constructor which takes String as a parameter.

I found and used java.util.Date's:

Label timeLabel = new Label(new SimpleDateFormat("HH:MM").format(new Date()));

but it shows the wrong time zone, so I'm going to use java.time and LocalTime class.

Is there any way to achieve same string result in one line? Thank You for your help :)

Answer

Manos Nikolaidis picture Manos Nikolaidis · Jun 22, 2017

It's probably better to use Java 8 types (java.time) in a new application. You can first create a DateTimeFormatter:

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm");

And then get the current time and format it:

Label timeLabel = new Label(LocalTime.now().format(dtf));