如何在java中获取带有时区的日期格式

1 java timezone datetime datetime-format date-formatting

我是 Java 新手。我想在文本末尾获取带有时区的日期格式。

2017-11-23T23:43:45-05:00[America/New_York]
Run Code Online (Sandbox Code Playgroud)

我现在拥有的是这个,我还想在那里添加用户的默认时区作为时区。这是我目前拥有的:

SimpleDateFormat trust = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.getDefault());
Run Code Online (Sandbox Code Playgroud)

这给了我(示例):

2018-08-17T22:39:39-0400
Run Code Online (Sandbox Code Playgroud)

Bas*_*que 6

tl;博士

ZonedDateTime                        // Represent a moment as seen in the wall-clock time used by the people of a particular region (a time zone). 
.now(                                // Capture the current moment.
    ZoneId.of( "America/New_York" )  // Specify the time zone through whose wall-clock time we want to perceive the current date and time.
)                                    // Returns a `ZonedDateTime` object.
.toString()                          // Generate text in standard ISO 8601 format extended to append the name of the time zone in square brackets.
Run Code Online (Sandbox Code Playgroud)

2017-11-23T23:43:45-05:00[美国/纽约]

ISO 8601

ISO 8601标准定义了表示日期时间值作为人类可读的文本许多实际格式。您所需格式的第一个块就是这样的标准格式:

2017-11-23T23:43:45-05:00

您所需的格式通过在方括号中附加时区名称来扩展标准格式。

2017-11-23T23:43:45-05:00[美国/纽约]

扩展的标准格式正是该ZonedDateTime::toString方法的行为。您会发现该类与 Java 捆绑在一起。

ZonedDateTime.now().toString()  // Generate text in standard ISO 8601 format extended to append the name of the time zone in square brackets.
Run Code Online (Sandbox Code Playgroud)

避免遗留的日期时间类

SimpleDateFormat类是被排挤年前由麻烦的旧日期时间类的一部分java.time类。永远不要使用这些糟糕的遗留类。

ZonedDateTime

获取特定地区(时区)的人们使用的挂钟时间中看到的当前时刻。

以、、 或等格式指定正确的时区名称。永远不要使用 3-4 个字母的缩写,例如或因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。continent/regionAmerica/MontrealAfrica/CasablancaPacific/AucklandESTIST

ZoneId z = ZoneId.of( "America/New_York" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
Run Code Online (Sandbox Code Playgroud)

生成String包含所需格式文本的对象。

String output = zdt.toString() ;  // Generate text in standard ISO 8601 format extended to append the name of the time zone in square brackets.
Run Code Online (Sandbox Code Playgroud)

关于java.time

java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date, Calendar, & SimpleDateFormat

现在处于维护模式Joda-Time项目建议迁移到java.time类。

要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310

您可以直接与您的数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC 驱动程序。不需要字符串,不需要类。java.sql.*

从哪里获得 java.time 类?

ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如IntervalYearWeekYearQuarter,和更多