I recently started using util.Date in Java, only to learn you cannot add/subtract days, and so I've now started to use LocalDate.
I have a web app that allows a user to enter a date in 'dd/MM/yyyy' format and it needs to be converted to 'yyyy-MM-dd'. The application also needs to throw an error if the entered date does not exist.
Below is a test application I'm using. It works, but wrongly allows dates like '31/02/2018'. I've tried adding '.withResolverStyle(ResolverStyle.STRICT)', but I get different errors.
package javaapplication1;
import java.text.ParseException;
import java.time.format.DateTimeFormatter;
import java.time.LocalDate;
import java.time.format.ResolverStyle;
public class JavaApplication1 {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
LocalDate date;
try {
String strDate = "31/2/09"; // Input from user
System.out.println("Form: " + strDate);
date = setDate(strDate, "d/M/yy");
System.out.println("Data: " + convertDateToString(date, "yyyy-MM-dd")); // Convert format for insertting into database
// If date is older than 1 year, output message
if (date.isBefore(today.minusYears(1))) {
System.out.println("Date is over a year old");
}
// If date is older than 30 days, output message
if (date.isBefore(today.minusDays(30))) {
System.out.println("Date is over 30 days old");
}
}
catch (ParseException e) {
System.out.println("Invalid date!");
e.printStackTrace();
}
}
private static LocalDate setDate(String strDate, String dateFormat) throws ParseException {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(dateFormat).withResolverStyle(ResolverStyle.STRICT);
//sdf.setLenient(false);
LocalDate date = LocalDate.parse(strDate, dtf);
return date;
}
private static String convertDateToString(LocalDate date, String dateFormat) {
//DateTimeFormatter dtf = DateTimeFormatter.ofPattern(dateFormat);
String strDate = date.toString();
return strDate;
}
}