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
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"
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.
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.
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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With