How to convert LocalDateTime object into ISO string including time zone?

本秂侑毒 提交于 2020-06-12 02:49:22

问题


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.

String -> 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 -> String

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:

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"


回答1:


LocalDateTime is offset/timezone agnostic class. You need an OffsetDateTime class.

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 -> 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")


来源:https://stackoverflow.com/questions/41656756/how-to-convert-localdatetime-object-into-iso-string-including-time-zone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!