(使用 Java 语法而不是 Scala)
tl;博士
我知道它对应的特定时区 (GMT-5)
GMT-5 不是时区,它是仅仅是偏移量。时区具有Continent/Region 格式的名称,例如Africa/Tunis。时区是区域使用的偏移量变化的历史记录。
您无法根据偏移量可靠地确定时区。许多时区可能在特定时刻共享相同的偏移量,但在其他时刻可能不同。所以你只会做一个疯狂的猜测。仅当您确定特定时区时才应用时区。
相反,使用偏移量本身来确定一个时刻,而不是一个区域。这是一个单行解决方案。
LocalDateTime // Represent a date with time-of-day but lacking the context of an offset-from-UTC or a time zone.
.parse( // When parsing, no need to specify a formatting pattern when the input complies with the ISO 8601 standard.
"2019-12-23 13:35:00".replace( " " , "T" ) // Comply with ISO 8601 standard formatting, replacing SPACE in the middle with an uppercase `T`.
) // Returns a `LocalDateTime` object.
.atOffset( // Determine a moment by placing the date and time-of-day of a `LocalDateTime` into the context of an offset-from-UTC.
ZoneOffset.ofHours( -5 ) // Represent an offset-from-UTC with `ZoneOffset`, merely a number of hours-minutes-seconds ahead or behind the prime meridian.
) // Returns a `OffsetDateTime` object.
.toString() // Generate text in standard ISO 8601 format.
Run code live.
2019-12-23T13:35-05:00
java.time
ISO 8601
您的输入字符串几乎采用 ISO 8601 标准格式。要遵守,请将中间的空格替换为T。
String input = "2019-12-23 13:35:00".replace( " " , "T" ) ;
LocalDateTime
鉴于您的输入缺少时区或与 UTC 的偏移量,请解析为 LocalDateTime。
LocalDateTime ldt = LocalDateTime.parse( input ) ;
请注意,LocalDateTime不是瞬间,不是时间轴上的一个点。在您大约下午 1:30 的示例中,我们不知道这是否意味着日本东京的下午 1:30 或美国俄亥俄州托莱多的下午 1:30,两个非常不同的时刻相隔数小时。
OffsetDateTime
您声称肯定知道此日期和时间是通过 UTC 后 5 小时偏移的镜头(通常在本初子午线以西)看到的。
ZoneOffset offset = ZoneOffset.ofHours( -5 ) ; // Five hours before UTC.
所以让我们应用ZoneOffset 来获得OffsetDateTime。
OffsetDateTime odt = ldt.atOffset( offset ) ;
看到这个code run live at IdeOne.com。
odt.toString(): 2019-12-23T13:35-05:00
ZonedDateTime
时区总是比仅仅偏移 UTC 更可取。偏移量是小时-分钟-秒数,仅此而已。时区更多。时区是特定地区的人们使用的偏移量的过去、现在和未来变化的历史。
但不要猜测时区。仅当您知道您的 LocalDateTime 对象最初用于该区域时才应用该区域。
以Continent/Region 的格式指定proper time zone name,例如America/Montreal、Africa/Casablanca 或Pacific/Auckland。切勿使用 2-4 个字母的缩写,例如 EST 或 IST,因为它们不是真正的时区,没有标准化,甚至不是唯一的 (!)。
ZoneId z = ZoneId.of( "America/Panama" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
关于java.time
java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.Date、Calendar 和 SimpleDateFormat。
要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310。
Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。
您可以直接与您的数据库交换 java.time 对象。使用符合JDBC 4.2 或更高版本的JDBC driver。不需要字符串,不需要java.sql.* 类。
从哪里获得 java.time 类?
ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是未来可能添加到 java.time 的试验场。您可以在这里找到一些有用的类,例如Interval、YearWeek、YearQuarter 和more。