How to calculate the number of days in a period?

后端 未结 3 1394
独厮守ぢ
独厮守ぢ 2020-11-27 19:10

For the following Period calculation:

Period.between(LocalDate.of(2015, 8, 1), LocalDate.of(2015, 9, 2))

the result is:

<
相关标签:
3条回答
  • 2020-11-27 19:47

    There's a specific object depending at the amount of time you'd like to deal with. This page here is very useful explaining which is best for your scenario.

    The ChronoUnit.between method is useful when you want to measure an amount of time in a single unit of time only, such as days or seconds

    LocalDate localDateStartDate = LocalDate.of(2016, 06, 10);
    LocalDate localDateEndDate = LocalDate.of(2016,06,23);
    long days = ChronoUnit.DAYS.between(localDateStartDate, localDateEndDate);
    
    0 讨论(0)
  • 2020-11-27 20:09

    From the documentation:

    To define an amount of time with date-based values (years, months, days), use the Period class. The Period class provides various get methods, such as getMonths, getDays, and getYears.To present the amount >of time measured in a single unit of time, such as days, you can use the ChronoUnit.between method.

    LocalDate today = LocalDate.now();
    LocalDate birthday = LocalDate.of(1960, Month.JANUARY, 1);
    
    Period p = Period.between(birthday, today);
    long p2 = ChronoUnit.DAYS.between(birthday, today);
    System.out.println("You are " + p.getYears() + " years, " + p.getMonths() +
                       " months, and " + p.getDays() +
                       " days old. (" + p2 + " days total)");
    

    The code produces output similar to the following:

    You are 53 years, 4 months, and 29 days old. (19508 days total)
    
    0 讨论(0)
  • 2020-11-27 20:09

    There is no way to do what you ask. The reason is that it is not possible from a Period to deduce the actual number of calendar days in the period. A Period is not tied to specific dates, once constructed in the way you show, it loses track of the actual calendar dates.

    For example your first period represents a period of 1 month and 1 day. But the period does not care which month. It is simply a concept of "a month and a day".

    If you need the number of days between two dates you should use ChronoUnit.DAYS.between as Saket Mittal writes.

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