如何在Java中使用时区获取日期格式

时间:2018-08-18 02:47:44

标签: java datetime timezone datetime-format date-formatting

我是Java新手。我想获得带日期区的日期格式,并在末尾输入文本。

2017-11-23T23:43:45-05:00[America/New_York]

我现在拥有的是,我还想将用户的默认时区添加为该时区的末尾。这是我目前拥有的:

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

哪个给我(示例):

2018-08-17T22:39:39-0400

4 个答案:

答案 0 :(得分:3)

tl; dr

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.
  

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.

避免使用旧的日期时间类

SimpleDateFormat类是麻烦的旧日期时间类的一部分,该类早在几年前就被 java.time 类所取代。永远不要使用这些糟糕的旧类。

ZonedDateTime

获取当前时刻,以特定地区(时区)的人们使用的挂钟时间显示。

continent/region的格式指定proper time zone name,例如America/MontrealAfrica/CasablancaPacific/Auckland。切勿使用3-4个字母的缩写,例如ESTIST,因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。

ZoneId z = ZoneId.of( "America/New_York" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;

生成一个String对象,其中包含所需格式的文本。

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

关于 java.time

java.time框架已内置在Java 8及更高版本中。这些类取代了麻烦的旧legacy日期时间类,例如java.util.DateCalendarSimpleDateFormat

目前位于Joda-Timemaintenance mode项目建议迁移到java.time类。

要了解更多信息,请参见Oracle Tutorial。并在Stack Overflow中搜索许多示例和说明。规格为JSR 310

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

在哪里获取java.time类?

ThreeTen-Extra项目使用其他类扩展了java.time。该项目为将来可能在java.time中添加内容提供了一个试验场。您可能会在这里找到一些有用的类,例如IntervalYearWeekYearQuartermore

答案 1 :(得分:0)

使用 yyyy-MM-dd'T'HH:mm:ssXXX 将时间打印为 2017-11-23T23:43:45-05:00 不是[America / New_York]的格式说明符。您可以使用[zzzz]将其打印为[东部标准时间],而不是[美国/纽约]

答案 2 :(得分:0)

给定的偏移量可以映射到多个名称,例如UTC-0500可以是America/New_YorkAmerica/TorontoAmerica/MontrealAmerica/Nassau(可能还有更多) 。选择正确的地理信息将需要更精确的地理信息,“正确的”也可能取决于其他因素。

这就是为什么没有简单的API返回此值,没有规范正确的答案的原因。您将必须决定自己的规则来确定字符串,然后使用TZ数据库检索它。

答案 3 :(得分:0)

这有帮助

DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZZ") .withLocale(Locale.ENGLISH);