问题
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.
回答1:
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
回答2:
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.
回答3:
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?
- Java SE 8 and SE 9 and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
- See How to use ThreeTenABP….
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.
回答4:
new DateTime().year().toInterval().toDuration().getStandardDays();
来源:https://stackoverflow.com/questions/9282419/how-can-i-get-the-number-of-days-in-a-year-using-jodatime