如何将LocalDateTime对象转换为包含时区的ISO字符串?

时间:2017-01-15 01:03:29

标签: kotlin datetime-format threetenbp

我正在尝试将日期/时间字符串来回转换为LocalDateTime对象。我使用ThreeTenBp作为日期/时间库。

字符串 - > 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"

1 个答案:

答案 0 :(得分:4)

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