Last active
November 8, 2016 10:57
-
-
Save dehora/9b2ce8bac22d1b37393d8b4f7c9eb7aa to your computer and use it in GitHub Desktop.
Handle leap seconds with DateTimeFormatter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package foo; | |
import java.time.Instant; | |
import java.time.OffsetDateTime; | |
import java.time.format.DateTimeFormatter; | |
import java.time.temporal.TemporalAccessor; | |
import java.time.temporal.TemporalQuery; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
class DateTimeSerdes { | |
private static final Logger logger = LoggerFactory.getLogger(DateTimeSerdes.class); | |
OffsetDateTime toOffsetDateTime(String raw) { | |
return toDateObject(raw, OffsetDateTime::from); | |
} | |
Instant toInstant(String raw) { | |
return toDateObject(raw, Instant::from); | |
} | |
private <T> T toDateObject(String raw, TemporalQuery<T> from) { | |
// hack to detect a leap | |
if (raw.contains(":59:60")) { | |
// ISO_INSTANT doesn't crash on leap seconds | |
TemporalAccessor parse = DateTimeFormatter.ISO_INSTANT.parse(raw); | |
if (parse.query(DateTimeFormatter.parsedLeapSecond())) { | |
logger.warn("saw leap second, shifting the date back 1s, {}", raw); | |
return DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse(raw.replace(":59:60", ":59:59"), | |
from); | |
} | |
} | |
return DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse(raw, from); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment