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

JJD picture JJD · Jan 15, 2017 · Viewed 11.2k times · Source

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"

Answer

s7vr picture s7vr · Jan 15, 2017

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