Joda DateTime - 在 DateTime 开始后整整一年或多年

Joda DateTime - get exactly one or multiple years after start DateTime

我有一个开始日期时间,我需要检查当前日期时间是否恰好是开始日期后的 1、2、3、4、5... 年。有谁知道如何做到这一点?

final DateTime start = formatter.parseDateTime("02.10.2015 09:00");
final DateTime end = formatter.parseDateTime("02.10.2016 08:00");

final Year years = Years.yearsBetween(start, end); //this isn't what i want but I have tried with Year object

在阅读了您在评论中的要求后,我删除了之前接受的答案:您想计算精确 日历 年的差异并且不确定如何处理闰年.

要求如下:

  • 2015-02-122016-02-12:相差1年
  • 2015-02-122017-02-12:相差2年
  • 2016-02-292018-02-28:相差2年
  • 2016-02-292020-02-29:相差4年

以上内容应涵盖所有边缘情况。这意味着在闰年的闰日(例如 2016 年 2 月 29 日)上加上正好一年将 return 2 月 28 日(根据示例为 2017 年)。大多数框架(我检查过的 Joda 和 .NET)都是这样处理的。

人们会期望在闰日上加一年(例如 2016 年 2 月 29 日)应该是 3 月 1 日而不是 2 月 28 日,因为 2016 年有 366 天,而下一个日子应该是 2 月 29 日年份是3月1日,但是我看到的不同的实现好像都不是。

我建议您坚持框架的做事方式。

DateTimeFormatter formatter = DateTimeFormat.forPattern("dd.MM.yyyy");
final LocalDate start = formatter.parseLocalDate("29.02.2016");
final LocalDate end = formatter.parseLocalDate("28.02.2019");

Period period = new Period(start, end, PeriodType.yearMonthDay());
boolean exactlyMultipleOfYears = period.getDays() == 0 && period.getMonths() == 0 && period.getYears() > 0;