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.
Another way to do it is to ask the
Calendar
class for the actual maximum days in a given year:This will return 366 for a bisestile year, 365 for a normal one.
Note, I used
getActualMaximum
instead ofgetMaximum
, which will always returns 366.The
GregorianCalendar
standar class has anisLeapyear()
method. If all you've got is a year number (say,2008
), then construct a date using this constructor, and then check theisLeapYear()
method afterwards.GregorianCalendar.isLeapYear(int year)
For DateTime calculations I highly recommend using the JodaTime library. For what you need, in particular, it would be a one liner:
I hope this helps.
You exact use case might be best solved with Joda and this specific example.
tl;dr
java.time
In Java 8 and later we have the java.time package. (Tutorial)
length
The
Year
class represents a single year value. You can interrogate its length.isLeap
You can also ask if a year is a Leap year or not.
As an example, get the number of days in year using Java’s ternary operator, such as:
In our case, we want number of days of year. That is 365 for non-Leap years, and 366 for Leap year.
Day-of-year
You can get the day-of-year number of a date. That number runs from 1 to 365, or 366 in a leap year.
Going the other direction, get a date for a day-of-year.
You could determine elapsed days by comparing these day-of-year numbers when dealing with a single year. But there is an easier way; read on.
Elapsed days
Use the
ChronoUnit
enum to calculate elapsed days.Automatically handles Leap Year.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as
java.util.Date
,Calendar
, &SimpleDateFormat
.The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as
Interval
,YearWeek
,YearQuarter
, and more.