Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting local time in java

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 :)

like image 262
Daniel Piskorz Avatar asked Jun 22 '17 13:06

Daniel Piskorz


People also ask

How do you format time in Java?

Solution: This example formats the time by using SimpleDateFormat("HH-mm-ss a") constructor and sdf. format(date) method of SimpleDateFormat class.

What is local time format?

LocalTime. Represents a time (hour, minute, second and nanoseconds (HH-mm-ss-ns)) LocalDateTime. Represents both a date and a time (yyyy-MM-dd-HH-mm-ss-ns) DateTimeFormatter.

What is the default format of local time in Java 8?

LocalTime LocalTime is an immutable class whose instance represents a time in the human readable format. It's default format is hh:mm:ss. zzz.

How do I format my LocalDate?

Default Pattern -> yyyy-MM-dd. If we use the LocalDate. toString() method then it formats the date in default format which is yyyy-MM-dd . The default pattern referenced in DateTimeFormatter.


1 Answers

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));
like image 150
Manos Nikolaidis Avatar answered Oct 19 '22 22:10

Manos Nikolaidis