Java calculate days in year, or between two dates

前端 未结 9 1641
慢半拍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: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;
    

提交回复
热议问题