Java calculate days in year, or between two dates

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

    You can use the TimeUnit class. For your specific needs this should do:

    public static int daysBetween(Date a, Date b) {
        final long dMs = a.getTime() - b.getTime();
        return TimeUnit.DAYS.convert(dMs, TimeUnit.MILLISECONDS);
    }
    

    Honestly, I don't see where leap years play any role in this calculation, though. Maybe I missed some aspect of your question?

    Edit: Stupid me, the leap years magic happens in the Date.getTime(). Anyway, you don't have to deal with it this way.

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

    GregorianCalendar.isLeapYear(int year)

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

    Another way to do it is to ask the Calendar class for the actual maximum days in a given year:

    Calendar cal = Calendar.getInstance();
    cal.setTime(new Date());
    
    int numOfDays = cal.getActualMaximum(Calendar.DAY_OF_YEAR);
    System.out.println(numOfDays);
    

    This will return 366 for a bisestile year, 365 for a normal one.

    Note, I used getActualMaximum instead of getMaximum, which will always returns 366.

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