Skip to content

Instantly share code, notes, and snippets.

@u1-liquid
Created August 8, 2023 10:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save u1-liquid/e5a75d66b2a0b97f2bc2ce5951941c78 to your computer and use it in GitHub Desktop.
Save u1-liquid/e5a75d66b2a0b97f2bc2ce5951941c78 to your computer and use it in GitHub Desktop.
Universal DateTime Pattern
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