获取java中两个日期之间的天数 [英] Getting the number of days between two dates in java

查看:2178
本文介绍了获取java中两个日期之间的天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您有日期格式的两个日期,如何获得两者之间的差距?

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

Date date1;
Date date2 ;
int numberDays = ?


推荐答案

建议使用JodaTime API进行日期: / p>

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/

敬意。

这篇关于获取java中两个日期之间的天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆