I've tried the following to no avail:
new Period(Years.ONE).getDays();
new Period(1, 0, 0, 000).getDays();
The answer I want is obviously 365.
I've tried the following to no avail:
new Period(Years.ONE).getDays();
new Period(1, 0, 0, 000).getDays();
The answer I want is obviously 365.
The answer you want isn't obviously 365
. It is either 365
or 366
, you don't take into account leap years in your example.
Detecting a leap year and just hard coding it with a ternary statement would be unacceptable for some reason?
final DateTime dt = new DateTime();
final int daysInYear = dt.year().isLeap() ? 366 : 365;
Of course this would give you the number of days in the current year, how to get number of days in a different year is trivial and a exercise for the reader.
If you want the real number of days for a given year:
int year = 2012;
LocalDate ld = new LocalDate(year,1,1);
System.out.println(Days.daysBetween(ld,ld.plusYears(1)).getDays());
Of course, this returns 365 or 366... normally:
int year = 1582;
LocalDate ld = new LocalDate(year,1,1,GJChronology.getInstance());
System.out.println(Days.daysBetween(ld,ld.plusYears(1)).getDays());
// year 1582 had 355 days
java.time.Year.of( 2017 ).length()
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
The java.time.Year
class can represent any particular year.
Year year = Year.of( 2017 );
You may interrogate for information about that year such as its length in number of days or whether it a Leap Year or not.
int countDaysInYear = year.length() ;
boolean isLeapYear = year.isLeap() ; // ISO proleptic calendar system rules.
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.