Created
August 8, 2023 10:46
-
-
Save u1-liquid/e5a75d66b2a0b97f2bc2ce5951941c78 to your computer and use it in GitHub Desktop.
Universal DateTime Pattern
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
private static final DateTimeFormatter universalDateTimePattern = DateTimeFormatter.ofPattern("[y-M-d[[' ']['T'][H[:m[:s[.SSSSSS][.SSS][.S]]]][' '][VV][zzz][OOOO][XXXXX]]][H[:m[:s[.SSSSSS][.SSS][.S]]]]"); | |
public static ZonedDateTime parseDateTime(String dateTime) { | |
try { | |
TemporalAccessor temporal = universalDateTimePattern.parseBest(dateTime, ZonedDateTime::from, OffsetDateTime::from, LocalDateTime::from, LocalDate::from, LocalTime::from); | |
if (temporal instanceof ZonedDateTime) return (ZonedDateTime) temporal; | |
else if (temporal instanceof OffsetDateTime) return ((OffsetDateTime) temporal).atZoneSameInstant(ZoneId.systemDefault()); | |
else if (temporal instanceof LocalDateTime) return ((LocalDateTime) temporal).atZone(ZoneId.systemDefault()); | |
else if (temporal instanceof LocalDate) return ((LocalDate) temporal).atStartOfDay(ZoneId.systemDefault()); | |
else if (temporal instanceof LocalTime) return ((LocalTime) temporal).atDate(LocalDate.now()).atZone(ZoneId.systemDefault()); | |
else return null; | |
} catch (Exception e) { | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment