我是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
答案 0 :(得分:3)
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标准定义了许多实用的格式,用于将日期时间值表示为人类可读的文本。所需格式的第一块就是这样的标准格式:
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/Montreal
,Africa/Casablanca
或Pacific/Auckland
。切勿使用3-4个字母的缩写,例如EST
或IST
,因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。
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 8及更高版本中。这些类取代了麻烦的旧legacy日期时间类,例如java.util.Date
,Calendar
和SimpleDateFormat
。
目前位于Joda-Time的maintenance 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中添加内容提供了一个试验场。您可能会在这里找到一些有用的类,例如Interval
,YearWeek
,YearQuarter
和more。
答案 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_York
或America/Toronto
或America/Montreal
或America/Nassau
(可能还有更多) 。选择正确的地理信息将需要更精确的地理信息,“正确的”也可能取决于其他因素。
这就是为什么没有简单的API返回此值,没有规范正确的答案的原因。您将必须决定自己的规则来确定字符串,然后使用TZ数据库检索它。
答案 3 :(得分:0)
这有帮助
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZZ") .withLocale(Locale.ENGLISH);