Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"

like image 541
JJD Avatar asked Jan 15 '17 01:01

JJD


People also ask

Does LocalDateTime have timezone?

The LocalDateTime class represents the date-time,often viewed as year-month-day-hour-minute-second and has got no representation of time-zone or offset from UTC/Greenwich.

How do I parse LocalDateTime?

parse(CharSequence text) parse() method of a LocalDateTime class used to get an instance of LocalDateTime from a string such as '2018-10-23T17:19:33' passed as parameter. The string must have a valid date-time and is parsed using DateTimeFormatter. ISO_LOCAL_DATE_TIME.

What is ISO-8601 date format Java?

The Date/Time API in Java works with the ISO 8601 format by default, which is (yyyy-MM-dd) . All Dates by default follow this format, and all Strings that are converted must follow it if you're using the default formatter.


1 Answers

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")
like image 109
s7vr Avatar answered Sep 28 '22 10:09

s7vr