Require a standard format for your user’s locale
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(
FormatStyle.MEDIUM, FormatStyle.SHORT)
.withLocale(Locale.UK);
ZoneId userTimeZone = ZoneId.of("Europe/London");
// Require a comma between date and time
String returnedFromWebPage = "2 Sep 2018, 09:00";
// Remove any space before the date or after the time
returnedFromWebPage = returnedFromWebPage.trim();
try {
ZonedDateTime dateTime = LocalDateTime.parse(returnedFromWebPage, formatter)
.atZone(userTimeZone);
if (dateTime.isBefore(ZonedDateTime.now(userTimeZone))) {
System.out.println("A valid date time");
} else {
System.out.println("Not in the past");
}
} catch (DateTimeParseException dtpe) {
System.out.println("Not a valid date time format");
}
Output when run on Java 10:
A valid date time
Java 10 with default locale data thinks that the a date and time notation in the UK may go like 2 Sep 2018, 09:00
(depending on how long or short you want it), that is, with a comma between date and time, otherwise like your input string. So one suggestion is to see whether your users could agree to that and enter the date and time in this way. If it is correct that this follows UK norms, I figure they’ll be happy to.
Now I don’t know whether your users are British at all. Java has localized formats for hundreds of locales. I think that you should first of all use your users’ locale. If they happen to speak Swahili, the standard format seems to be without the comma:
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(
FormatStyle.MEDIUM, FormatStyle.SHORT)
.withLocale(Locale.forLanguageTag("sw"));
ZoneId userTimeZone = ZoneId.of("Africa/Nairobi");
String returnedFromWebPage = "2 Sep 2018 09:00";
With these changes the code also prints A valid date time
.
If required build your own formatter
If your users are not happy with any of the built-in formats in Java, you will need to specify the format they want to use:
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("d MMM uuuu HH:mm", Locale.ENGLISH);
String returnedFromWebPage = "2 Sep 2018 09:00";
This will also cause the code to print A valid date time
.