I get two strings and I must transform them into dates and show the difference in days between them. But I must throw an exception if one of the two dates is invalid.
This is the code I have so far for this task:
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String d1 = sc.next();
String d2 = sc.next();
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
try {
Date date1 = formatter.parse(d1);
Date date2 = formatter.parse(d2);
long dt = (date1.getTime() - date2.getTime()) + 3600000;
long days = (dt / 86400000L);
System.out.println(days);
} catch (ParseException e) {
System.out.println("Data inválida");
e.printStackTrace();
}
}
}
But if I enter an invalid date like 02/29/2021
, it converts to 03/01/2021
instead of throwing the exception.