在java中格式化本地时间 [英] Formatting local time in java

查看:165
本文介绍了在java中格式化本地时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建我的JavaFX应用程序,每次创建新列表单元格时都需要使用时间标签。我需要将当前时间的字符串以 HH:MM 格式直接放入Label构造函数中,该构造函数将 String 作为参数。

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.

我找到并使用了 java.util.Date 的:

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

但它显示错误的时区,所以我将使用 java.time LocalTime class。

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

推荐答案

使用Java 8类型(java.time)可能更好一个新的应用程序您可以先创建 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));

这篇关于在java中格式化本地时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆