LocalDate minus a Period get wrong result

后端 未结 1 535
挽巷
挽巷 2021-02-09 15:56

LocalDate minus a Period(like \"28 years, 1 months and 27 days\"),get wrong result.

But minus a Period(only have days unit ,like \

相关标签:
1条回答
  • 2021-02-09 16:22

    Your case can be simplified to

    LocalDate date1 = LocalDate.of(2017, 2, 22), date2 = LocalDate.of(2017, 4, 18);
    Period p = Period.between(date1, date2);
    System.out.println("date1 + p: "+date1.plus(p));
    System.out.println("date2 - p: "+date2.minus(p));
    

    which will print

    date1 + p: 2017-04-18
    date2 - p: 2017-02-19
    

    In other words, the number of years is irrelevant (unless one of the years involved is a leap year and the other isn’t, but here, both aren’t). The following illustrates the issue:

    February                       March                                                                                        April
    19 20 21 22 23 24 25 26 27 28  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18
     ↑        │                                                                                   ↑                                                                                ↑
     │        └──────────────────────────── plus one Month ───────────────────────────────────────┴───────────────────────── plus 27 days ─────────────────────────────────────────┤
     │                                                                                ↑                                                                                            ↓
     └───────────────────────── minus 27 days ────────────────────────────────────────┴─────────────────── minus one month ────────────────────────────────────────────────────────┘
    

    This will change, if you swap the direction:

    Period p2 = Period.between(date2, date1);
    System.out.println("date1 - p2: "+date1.minus(p2));
    System.out.println("date2 + p2: "+date2.plus(p2));
    

    which will print

    date1 - p2: 2017-04-15
    date2 + p2: 2017-02-22
    

    So when you express a period in terms of years, month and days, the direction becomes relevant. In contrast, the plain number of days between two dates is invariant:

    LocalDate date1 = LocalDate.of(2017, 2, 22), date2 = LocalDate.of(2017, 4, 18);
    Period p = Period.ofDays((int)ChronoUnit.DAYS.between(date1, date2));
    System.out.println("date1 + p: "+date1.plus(p));
    System.out.println("date2 - p: "+date2.minus(p));
    
    date1 + p: 2017-04-18
    date2 - p: 2017-02-22
    
    0 讨论(0)
提交回复
热议问题