Search code examples
javadatedatetimechronounit

Get count day between to date Java


Hello i need to get count day between to date using ChronoUnit

this is my code :

            Date madate = rfxobjet.getRv_rc_date();
            Date date=java.util.Calendar.getInstance().getTime();
            Date res=null;
            int day = ChronoUnit.DAYS.between(madate,date);

but i got this error : The method between(Temporal, Temporal) in the type ChronoUnit is not applicable for the arguments (Date, Date)

please what i should to do i need to resolve this error


Solution

  • You mix different API. Date is an old class which was in Java since JDK 1. While ChronoUnit is from newer date API appeared first from JDK8. Normally you should use newer API. It means that instead of Date you should use LocalDate (or LocalDateTime) which is part of the new API.

    So in order to correct your code you need to make so that madate and date are both instances of LocalDate. E.g. this should work:

    LocalDate madate = LocalDate.now();
    LocalDate date = LocalDate.now();
    long day = ChronoUnit.DAYS.between(madate, date);
    

    Or if you need still need to use Date objects you can convert them to Temporal objects:

    Date madate = rfxobjet.getRv_rc_date();
    Date date = java.util.Calendar.getInstance().getTime();
    long day = ChronoUnit.DAYS.between(madate.toInstant(), date.toInstant());
    

    Temporal is a base class for LocalDate and LocalDateTime so using Date.toInstant() you essentially convert date to corresponding instance in new API.

    NB. between() returns long so the day variable also needs to be of type long or you need to use to int conversion:

    int day = (int) ChronoUnit.DAYS.between(madate, date);