Java calculate days in year

2019-03-24 06:20发布

Is there a method in any native Java class to calculate how many days were/will be in a specific year? As in, was it a Leap year (366 days) or a normal year (365 days)?

Or do I need to write it myself?

I'm calculating the number of days between two dates, for example, how many days left until my birthday. I want to take into account the February 29 of Leap year. I have it all done except that 29th.

8条回答
Melony?
2楼-- · 2019-03-24 06:50

You can use the TimeUnit class. For your specific needs this should do:

public static int daysBetween(Date a, Date b) {
    final long dMs = a.getTime() - b.getTime();
    return TimeUnit.DAYS.convert(dMs, TimeUnit.MILLISECONDS);
}

Honestly, I don't see where leap years play any role in this calculation, though. Maybe I missed some aspect of your question?

Edit: Stupid me, the leap years magic happens in the Date.getTime(). Anyway, you don't have to deal with it this way.

查看更多
Evening l夕情丶
3楼-- · 2019-03-24 06:51

You can look at the Wikipedia page for some very nice pseudocode:

if year modulo 400 is 0
       then is_leap_year
else if year modulo 100 is 0
       then not_leap_year
else if year modulo 4 is 0
       then is_leap_year
else
       not_leap_year

I'm sure you can figure out how to implement that logic in Java. :-)

查看更多
登录 后发表回答