Java calculate days in year, or between two dates

前端 未结 9 1642
慢半拍i
慢半拍i 2021-02-07 04:48

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)?

相关标签:
9条回答
  • 2021-02-07 05:04

    You exact use case might be best solved with Joda and this specific example.

    0 讨论(0)
  • 2021-02-07 05:07

    since JAVA 8

    Days in a year:

    LocalDate d = LocalDate.parse("2020-12-31");                   // import java.time.LocalDate;
    return d.lengthOfYear();                                       // 366
    

    Days to my birthday:

    LocalDate birth = LocalDate.parse("2000-02-29");
    LocalDate today = LocalDate.now();                             // or pass a timezone as the parameter
    
    LocalDate thisYearBirthday = birth.withYear(today.getYear());  // it gives Feb 28 if the birth was on Feb 29, but the year is not leap.
    LocalDate nextBirthday = today.isAfter(thisYearBirthday)
        ? birth.withYear(today.getYear() + 1)
        : thisYearBirthday;
    
    return DAYS.between(today, nextBirthday);                      // import static java.time.temporal.ChronoUnit.DAYS;
    
    0 讨论(0)
  • 2021-02-07 05:11

    tl;dr

    Year.of( 2015 ).length()
    

    …and…

    Year.isLeap( 2015 )
    

    java.time.Year

    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.

    int daysInYear = Year.of( 2015 ).length();
    

    isLeap

    You can also ask if a year is a Leap year or not.

    Boolean isLeapYear = Year.isLeap( 2015 );
    

    As an example, get the number of days in year using Java’s ternary operator, such as:

    minVal = (a < b) ? a : b;

    In our case, we want number of days of year. That is 365 for non-Leap years, and 366 for Leap year.

    int daysInYear = ( Year.isLeap( 2015 ) ) ? 366 : 365 ;
    

    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.

    int dayOfYear = LocalDate.now( ZoneId.of( "America/Montreal" ).getDayOfYear() ;
    

    Going the other direction, get a date for a day-of-year.

    Year.now( ZoneId.of( "America/Montreal" ) ).atDay( 159 ) ;
    

    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.

    LocalDate start = LocalDate.of( 2017 , 2 , 23 ) ;
    LocalDate stop = LocalDate.of( 2017 , 3 , 11 ) ;
    int daysBetween = ChronoUnit.DAYS.between( start , stop );
    

    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?

    • Java SE 8, Java 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 Java 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.

    0 讨论(0)
  • 2021-02-07 05:12

    The GregorianCalendar standar class has an isLeapyear() method. If all you've got is a year number (say, 2008), then construct a date using this constructor, and then check the isLeapYear() method afterwards.

    0 讨论(0)
  • 2021-02-07 05:12

    For DateTime calculations I highly recommend using the JodaTime library. For what you need, in particular, it would be a one liner:

    Days.daysBetween(date1, date2).getDays();
    

    I hope this helps.

    0 讨论(0)
  • 2021-02-07 05:13

    You can look at the Wikipedia page for some very nice pseudocode:

    if year modulo 400 is 0
           then is_leap_year
    else if year modulo 100 is 0
           then not_leap_year
    else if year modulo 4 is 0
           then is_leap_year
    else
           not_leap_year
    

    I'm sure you can figure out how to implement that logic in Java. :-)

    0 讨论(0)
提交回复
热议问题