Skip to content

Instantly share code, notes, and snippets.

@ariesmcrae
Last active February 16, 2018 07:11
Show Gist options
  • Save ariesmcrae/df53f9b423246e42b2021e8eeb4312b0 to your computer and use it in GitHub Desktop.
Save ariesmcrae/df53f9b423246e42b2021e8eeb4312b0 to your computer and use it in GitHub Desktop.
Convert string to LocalDate in Java 8+
/**
* Performs date validation and conversion of String to LocalDate.<br/>
* If valid, then date string is converted to LocalDate.
* @param input Date string in format.
* @return the LocalDate.
*/
public static LocalDate toDate(String date) {
if (date == null || date.trim().length() == 0) {
throw new RuntimeException("Date input can't be null.");
}
DateTimeFormatter formatter = null;
LocalDate localDate = null;
try {
formatter = new DateTimeFormatterBuilder()
.appendPattern("[dd/MM/yyyy]")
.appendPattern("[dd/MM/yy]")
.appendPattern("[dd/M/yyyy]")
.appendPattern("[dd/M/yy]")
.appendPattern("[d/MM/yyyy]")
.appendPattern("[d/MM/yy]")
.appendPattern("[d/M/yyyy]")
.appendPattern("[d/M/yy]")
.toFormatter();
localDate = LocalDate.parse(date.trim(), formatter);
} catch (Exception e) {
throw new RuntimeException("Date is invalid. "
+ "It could be out of bounds. Please correct the format. "
+ "Accepted formats are dd/MM/yyyy, dd/MM/yy, dd/M/yyyy, dd/M/yy "
+ "d/MM/yyyy, d/MM/yy, d/M/yyyy, d/M/yy. " + e);
}
return localDate;
}
// Note: This is how you get the current date/time in ISO8601 format in UTC (Zulu) timezone
// private String dateTimeNowInISO = ZonedDateTime.now().format(DateTimeFormatter.ISO_INSTANT);
// output: 2018-01-16T20:17:02.186Z
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment