如何将LocalDateTime对象转换为包括时区的ISO字符串? [英] How to convert LocalDateTime object into ISO string including time zone?
问题描述
我正在尝试将日期/时间字符串来回转换为LocalDateTime
对象.我正在使用 ThreeTenBp 作为日期/时间库.
I am trying to convert a date/time string back and forth into a LocalDateTime
object. I am using ThreeTenBp as the date/time library.
val actual = LocalDateTime.parse("2016-12-27T08:15:05.674+01:00",
DateTimeFormatter.ISO_DATE_TIME)
val expected = LocalDateTime.of(2016, 12, 27, 8, 15, 5, 674000000)
assertThat(actual).isEqualTo(expected) // Successful
LocalDateTime->字符串
val dateTime = LocalDateTime.of(2016, 12, 27, 8, 15, 5, 674000000)
val actual = dateTime.format(DateTimeFormatter.ISO_DATE_TIME)
assertThat(actual).isEqualTo("2016-12-27T08:15:05.674+01:00") // Fails
由于某些原因缺少时区:
For some reason the time zone is missing:
预期:< ... 6-12-27T08:15:05.674 [+01:00]>但是:< ... 6-12-27T08:15:05.674 []">
预期:"2016-12-27T08:15:05.674 + 01:00"
实际:"2016-12-27T08:15:05.674"
expected: <...6-12-27T08:15:05.674[+01:00]"> but was:<...6-12-27T08:15:05.674[]">
Expected :"2016-12-27T08:15:05.674+01:00"
Actual :"2016-12-27T08:15:05.674"
推荐答案
LocalDateTime
是与偏移量/时区无关的类.您需要一个OffsetDateTime
类.
LocalDateTime
is offset/timezone agnostic class. You need an OffsetDateTime
class.
字符串-> OffsetDateTime
String -> OffsetDateTime
val actual = OffsetDateTime.parse("2016-12-27T08:15:05.674+01:00", DateTimeFormatter.ISO_DATE_TIME)
val expected = OffsetDateTime.of(2016, 12, 27, 8, 15, 5, 674000000, ZoneOffset.of("+01:00"))
assertThat(actual).isEqualTo(expected)
OffsetDateTime->字符串
OffsetDateTime -> String
val dateTime = OffsetDateTime.of(2016, 12, 27, 8, 15, 5, 674000000, ZoneOffset.of("+01:00"))
val actual = dateTime.format(DateTimeFormatter.ISO_DATE_TIME)
assertThat(actual).isEqualTo("2016-12-27T08:15:05.674+01:00")
这篇关于如何将LocalDateTime对象转换为包括时区的ISO字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!