Search code examples
javadatedate-formatparseexception

Calculating days between two dates in JAVA (catch ParseException error)


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.


Solution

  • Don't use Date. Try this.

            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy");
            String date1 = "11/11/2020";
            String date2 = "13/11/2020";
    
            LocalDate d1 = LocalDate.parse(date1,dtf);
            LocalDate d2 = LocalDate.parse(date2,dtf);
    
            long ndays = d1.datesUntil(d2).count();
            System.out.println(ndays);