java 两个日期天数差,Java中两个日期之间的天数差异?

I need to find the number of days between two dates: one is from a report and one is the current date. My snippet:

int age=calculateDifference(agingDate, today);

Here calculateDifference is a private method, agingDate and today are Date objects, just for your clarification. I've followed two articles from a Java forum, Thread 1 / Thread 2.

It works fine in a standalone program although when I include this into my logic to read from the report I get an unusual difference in values.

Why is it happening and how can I fix it?

EDIT :

I'm getting a greater number of days compared to the actual amount of Days.

public static int calculateDifference(Date a, Date b)

{

int tempDifference = 0;

int difference = 0;

Calendar earlier = Calendar.getInstance();

Calendar later = Calendar.getInstance();

if (a.compareTo(b) < 0)

{

earlier.setTime(a);

later.setTime(b);

}

else

{

earlier.setTime(b);

later.setTime(a);

}

while (earlier.get(Calendar.YEAR) != later.get(Calendar.YEAR))

{

tempDifference = 365 * (later.get(Calendar.YEAR) - earlier.get(Calendar.YEAR));

difference += tempDifference;

earlier.add(Calendar.DAY_OF_YEAR, tempDifference);

}

if (earlier.get(Calendar.DAY_OF_YEAR) != later.get(Calendar.DAY_OF_YEAR))

{

tempDifference = later.get(Calendar.DAY_OF_YEAR) - earlier.get(Calendar.DAY_OF_YEAR);

difference += tempDifference;

earlier.add(Calendar.DAY_OF_YEAR, tempDifference);

}

return difference;

}

Note :

Unfortunately, none of the answers helped me solve the problem. I've accomplished this problem with the help of Joda-time library.

解决方案

I would suggest you use the excellent Joda Time library instead of the flawed java.util.Date and friends. You could simply write

import java.util.Date;

import org.joda.time.DateTime;

import org.joda.time.Days;

Date past = new Date(110, 5, 20); // June 20th, 2010

Date today = new Date(110, 6, 24); // July 24th

int days = Days.daysBetween(new DateTime(past), new DateTime(today)).getDays(); // => 34

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值