Last active
February 16, 2018 07:11
-
-
Save ariesmcrae/df53f9b423246e42b2021e8eeb4312b0 to your computer and use it in GitHub Desktop.
Convert string to LocalDate in Java 8+
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
/** | |
* 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