Java calculate days in year, or between two dates

jurchiks picture jurchiks · Jan 24, 2011 · Viewed 40.7k times · Source

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.

Answer

Trasplazio Garzuglio picture Trasplazio Garzuglio · Sep 17, 2012

Another way to do it is to ask the Calendar class for the actual maximum days in a given year:

Calendar cal = Calendar.getInstance();
cal.setTime(new Date());

int numOfDays = cal.getActualMaximum(Calendar.DAY_OF_YEAR);
System.out.println(numOfDays);

This will return 366 for a bisestile year, 365 for a normal one.

Note, I used getActualMaximum instead of getMaximum, which will always returns 366.