How can I get the number of days in a year using JodaTime?

I tried the following to no avail:

new Period(Years.ONE).getDays();

new Period(1, 0, 0, 000).getDays();

The answer, I obviously want 365.

+5
source share
4 answers

If you want the actual 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 ... usually:

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
+8
source

The answer you want is not explicit 365. This either 365, or 366, you do not consider leap years in your example.

Detecting a leap year and simply hard-coding it with a ternary statement would be unacceptable for any reason?

final DateTime dt = new DateTime();
final int daysInYear = dt.year().isLeap() ? 366 : 365;

Of course, this will give you the number of days in the current year, how to get the number of days in another year is trivial and an exercise for the reader.

+12

TL;DR

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

java.time

Joda-Time, , java.time.

java.time.Year .

Year year = Year.of( 2017 );

, , Leap Year .

int countDaysInYear = year.length() ;
boolean isLeapYear = year.isLeap() ; // ISO proleptic calendar system rules.

java.time

java.time Java 8 . legacy , java.util.Date, Calendar SimpleDateFormat.

Joda-Time, , java.time.

, . Oracle. Qaru . JSR 310.

java.time?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proof of possible future additions to java.time. Here you can find useful classes, such as Interval, YearWeek, YearQuarterand longer .

+3
source

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

+2
source

All Articles