Getting the number of days between two dates in ja

2019-02-20 10:23发布

问题:

This question already has an answer here:

  • Calculating the difference between two Java date instances 45 answers
  • Calculate date/time difference in java [duplicate] 17 answers

Hi have two dates in date format, how do i get the difference of days between the two ?

Date date1;
Date date2 ;
int numberDays = ?

回答1:

The recommendation is to use JodaTime API for Dates:

import java.util.logging.Logger;

import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.joda.time.Interval;

public class DatesInterval {
    private final static Logger log = Logger.getLogger(DatesInterval.class.getName());
    public static void main(String[] args) {
        //creates a date 10 days ago in JodaTime
        DateTime daysAgo10 = new DateTime().minusDays(10);
        //today
        DateTime today = new DateTime();

        //create an interval in Joda
        Interval interval = new Interval(daysAgo10.getMillis(), today.getMillis());
        //than get the duration
        Duration duration = interval.toDuration();

        //now you can get what you want. As you can imagine you can get days, millis, whateaver you need. 
        log.info("Difference in days: " + duration.getStandardDays());
    }
}

http://joda-time.sourceforge.net/

regards.