6

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.

David M. Coe
  • 309
  • 1
  • 6
  • 14

4 Answers4

12

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.

10

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
leonbloy
  • 73,180
  • 20
  • 142
  • 190
5

tl;dr

java.time.Year.of( 2017 ).length()

Using java.time

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.

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.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
4

new DateTime().year().toInterval().toDuration().getStandardDays();