I am trying to implement an expiration date detector in java, for this, I need to compare the local date of the computer (today), with an expiration date (Date).
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date expirationDate;
Temporal today;
String expiration = ("27/12/2021"); //Expiration date of a product
try {
expirationDate = format.parse(expiration);
today = LocalDate.now();
} catch (ParseException e) {
e.printStackTrace();
}
¿How can I compare these two dates?
CodePudding user response:
If you can, use the newer java.time API for doing this sort of thing. What you are using is pretty much obsolete already. Something like this should do the trick:
public static boolean isProductExpired (String productDate, java.util.Locale theLocale) {
java.time.format.DateTimeFormatter formatter =
java.time.format.DateTimeFormatter.ofPattern("dd/MM/yyyy", theLocale);
java.time.LocalDate date1 = java.time.LocalDate.parse(productDate, formatter);
java.time.LocalDate date2 = java.time.LocalDate.now();
return date2.isAfter(date1);
}
To use the above method:
String productDate = "27/12/2021"; //Expiration date of a product
System.out.println(isProductExpired(productDate, java.util.Locale.ENGLISH));
CodePudding user response:
The problem has been solved.
Just convert LocalDate to Date
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date expirationDate;
expirationDate = format.parse("08/12/2020");
Date today = Date.from(LocalDate.now().atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
if (today.before(expirationDate)) {
//Condition Expiration
}