Note that I was addicted to the title when trying to serialize and deserialize with Java8 LocalDateTime
and Java6 Date
via JSON.
As an image, I tried to do the following across the projects.
Java8 DateTime -> (Serialize) -> JSON -> (Deserialize) -> Java6 Date
Then, the difference between the possible range of values between LocalDateTime
and Date
appears. Specifically, what happens is that when you deserialize something with a range of values that cannot be represented by Date
, such as LocalDateTime.MIN
, the original value is lost.
More specifically, it will be as follows.
import java.time.LocalDateTime
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
import java.util.Date
import java.text.SimpleDateFormat
fun main(args: Array<String>) {
val formatter = SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss")
val minLocalDateTime = formatter.format(formatter.parse(
DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(LocalDateTime.MIN)))
val minDateText = formatter.format(Date(Long.MIN_VALUE))
val zeroDateText = formatter.format(Date(0L))
val zeroEpocLocalDateTime = formatter.format(formatter.parse(
DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(
LocalDateTime.ofEpochSecond(0L, 0, ZoneOffset.UTC))))
println (
"""Java8 DateTime | LocalDateTime.MIN | ${LocalDateTime.MIN}
Java6 Date | LocalDateTime.MIN | $minLocalDateTime
Java6 Date | Date(Long.MIN_VALUE) | $minDateText
Java6 Date | Date(0L) | $zeroDateText
Java8 DateTime | ofEpochSecond(0L, 0,) | $zeroEpocLocalDateTime
""")
}
Execution result.
Java8 DateTime | LocalDateTime.MIN | -999999999-01-01T00:00
Java6 Date | LocalDateTime.MIN | 169087565-03-15T04:51:43
Java6 Date | Date(Long.MIN_VALUE) | 292269055-12-02T04:47:04
Java6 Date | Date(0L) | 1970-01-01T12:00:00
Java8 DateTime | ofEpochSecond(0L, 0,) | 1970-01-01T12:00:00
As already mentioned in the execution result, epoch time is used to absorb this difference.
Compatibility is maintained by setting the minimum value on the side that uses LocalDateTime
to the minimum value in epoch time.
You can get the minimum epoch time by using LocalDateTime.ofEpochSecond (0L, 0, ZoneOffset.UTC)
, so on the side of using LocalDateTime
, you can use it to use Java6. You will be able to make it compatible with your project.
Recommended Posts