Getting the number of days between two dates in ja

2019-02-20 10:22发布

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条回答
够拽才男人
2楼-- · 2019-02-20 10:50

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.

查看更多
登录 后发表回答