提问人:JJD 提问时间:1/15/2017 更新时间:1/15/2017 访问量:29727
如何将LocalDateTime对象转换为包含时区的ISO字符串?
How to convert LocalDateTime object into ISO string including time zone?
问:
我正在尝试将日期/时间字符串来回转换为对象。我正在使用 ThreeTenBp 作为日期/时间库。LocalDateTime
字符串 -> LocalDateTime
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
由于某种原因,时区丢失:
预期:<...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”
答:
24赞
s7vr
1/15/2017
#1
LocalDateTime
是与偏移量/时区无关的类。你需要一个类。OffsetDateTime
字符串 -> 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 -> 字符串
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")
评论
0赞
atul ranjan
9/8/2021
我们可以使用 Annotation 来反序列化吗?即 @SomeDeserializeAnnotation LocalDateTime incomingIso8601DateTime; ?
评论