【问题标题】:Get difference between two dates in years - without months - without days获取年中两个日期之间的差异 - 没有月 - 没有天
【发布时间】:2014-10-02 11:27:18
【问题描述】:

我在Joda-Time 中使用以下函数来获取两个日期之间的差异:

public static int getDiffYear(Date first) {
    int yearsBetween = Years.yearsBetween(new DateTime(first), new DateTime()).getYears();
    return yearsBetween;
}

提供给函数的日期是:0001-10-02 (YYYY-MM_DD)

我得到了与今天对比的 2013 年的差异,但是我发现正确的结果应该是 2012 年。因为这一天仍然是 01。

我在纯 Java 中有一个单独的函数,得到了想要的结果:

public static int getDiffYear(Date first) {
        Calendar a =  Calendar.getInstance();
        a.setTime(first);
        Calendar b = Calendar.getInstance();
        int diff = b.get(Calendar.YEAR) - a.get(Calendar.YEAR);
        if (a.get(Calendar.MONTH) > b.get(Calendar.MONTH) || 
                (a.get(Calendar.MONTH) == b.get(Calendar.MONTH) && a.get(Calendar.DATE) > b.get(Calendar.DATE))) {
            diff--;
        }
        return diff;
    }

【问题讨论】:

  • 请解释为什么 2014 - 1 应该是 2012。Sans 表示没有。
  • 您还应该确保充分了解 Proleptic 公历的后果。 en.wikipedia.org/wiki/…
  • 好吧,我很困惑,我正在重现上面的纯Java函数。我想要 Joda 的等价物。不是在做功课方面,但除了年我什么都不占。
  • 我很抱歉命名约定被搞砸了。
  • 顺便说一句,Joda-Time 也是“纯 Java”。

标签: java jodatime


【解决方案1】:

Joda 将与yearsBetween 一起考虑几天。试试这个:

public static int getDiffYear() {
    LocalDate firstDate = new LocalDate(1, 10, 2);
    LocalDate today = new LocalDate();
    int yearsBetween = Years.yearsBetween(firstDate, today).getYears();

    return yearsBetween;
}

从今天(2014 年 10 月 1 日)开始,它将返回 2012 年。这表明从java.util.Date 的转换中发生了一些事情。

编辑:这是由于 Marko Topolnik mentioned。当您执行 new DateTime(first) 时,您将获得 0001-09-30 的 DateTime

【讨论】:

    【解决方案2】:

    Years 实用程序类将仅检查年份差异。如果您需要考虑天数,您应该使用Days 类并将结果重新计算为年。

    【讨论】:

    • 我不需要照顾日子,只要几年。
    • 是的,但您要考虑一年中的哪一天。 Years 类将计算第 1 年和 2014 年之间的差异。您要验证它是 2014 年 10 月 1 日,所以它不是 2013 年,但明天会是。
    • 那么在这方面有什么提示吗?
    • 另外,如果在几天内完成,我认为考虑闰年会很痛苦。
    猜你喜欢
    • 2013-07-23
    • 2014-04-07
    • 2022-10-02
    • 2021-09-06
    • 2013-07-17
    • 2014-12-03
    • 2014-12-06
    相关资源
    最近更新 更多