I’m trying to calculate the number of days between 2 dates. When I run this, it throws the catch (ParseException ex).
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) {
String date1 = "11/11/2020";
String date2 = "13/11/2020";
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-mm-yyyy");
Date date_1 = dateFormat.parse(date1);
Date date_2 = dateFormat.parse(date2);
System.out.println(date_1);
System.out.println(date_2);
long numberOfDays = date_2.getTime() - date_1.getTime();
numberOfDays = TimeUnit.DAYS.convert(numberOfDays, TimeUnit.MILLISECONDS);
System.out.println(numberOfDays);
}
catch (ParseException ex)
{
System.out.println("error");
}
}
}
other than the catch, there are no errors, so I’m kind of lost.
e.printStackTrace();instead ofSystem.out.println("error");Dateis quitedeprecatedand should not be used.LocalDateis the way to go for date related code.SimpleDateFormatandDate. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Also converting milliseonds to days may give inaccurate results across summer time (DST) transistions and similar. Instead useLocalDate,DateTimeFormatterandChronoUnit.DAYS.between(), all from java.time, the modern Java date and time API.