获取java中两个日期之间的天数

时间:2013-03-21 19:39:59

标签: java date numbers days

你有两个日期格式的日期,我如何得到两者之间的天数差异?

Date date1;
Date date2 ;
int numberDays = ?

1 个答案:

答案 0 :(得分:-4)

建议使用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/

问候。