Given any date/time format (passed by the user), I need to parse the date with it and return milliseconds since java epoch, something that could be done with the following code using old date API:
//dateFormatter is SimpleDateFormat
Date d = dateFormatter.parse(value);
return d.getTime();
The only requirement for the format that it will contain the date part, for example all of the following are possible formats:
"dd/MM/yyyy"
"dd/MM/yyyy HH:mm X" //with timezone
The missing part are completed with start of the day/local time zone. So I came up with the following, which seems to be much more verbose and not sure if there is a more efficient way to do it:
//dateFormatter is DateTimeFormatter
TemporalAccessor ta = dateFormatter.parse(value);
LocalDate ld = LocalDate.from(ta); //assume must have date part
LocalTime lt = ta.query(TemporalQueries.localTime());
if (lt == null) {
lt = LocalTime.MIN;
}
ZoneId zoneId = ta.query(TemporalQueries.zone());
if (zoneId == null) {
zoneId = ZoneId.systemDefault();
}
Instant d = LocalDateTime.of(ld, lt).atZone(zoneId).toInstant();
return d.toEpochMilli();