开发者

How can I learn how many days passed from a specific date?

How can I learn how m开发者_运维问答any days passed from a spesific date? Which package i need to use and how?


Just for the protocol - i love java.util.concurrent.TimeUnit for that things.

Date d1 = ...
Date d2 = ...
long dif = d1.getTime() - d2.getTime();
long days = TimeUnit.MILLISECONDS.toDays(dif);

So basically exactly what the answer from morja is, but using TimeUnit for calculating time things around. Having values like 24, 60 etc. directly in your code violates Java Code Conventions (which only allow -1, 0 and 1 directly in code) and is harder to read.


EDIT My previous answer was only valid within a year.

You can use the milliseconds difference like this:

Date date1 = // some date
Date date2 = // some other date
long difference = date2.getTime() - date1.getTime();
long differenceDays = difference / (1000 * 60 * 60 * 24);

Basically the same as timbooo answered, just a shorter way.


Check out this example by kodejava.org


Jodatime makes such calculations a lot simpler:

Date now = // some Date
Date then = // some Date
int days = Days.daysBetween(new DateTime(now), new DateTime(then)).getDays();


In fact, you should create instances of Calendar from both of the dates, getTimeInMillis() from both of them (that is, time in milliseconds since 1970), substract one from the other, divide by 1000/seconds-a-minute/minute-an-hour/hour-a-day. There is your answer ;)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜