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 :)
Solution: This example formats the time by using SimpleDateFormat("HH-mm-ss a") constructor and sdf. format(date) method of SimpleDateFormat class.
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.
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.
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With