乔达时间 period.getMonths() 始终为 0

joda time period.getMonths() is always 0

我正在尝试计算日期之间的差异,例如几小时前、几分钟前、几个月前……

SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
        "dd/M/yyyy HH:mm:ss");

Date now = null;
try {
    now = simpleDateFormat.parse(simpleDateFormat.format(new Date()));
} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
Date time = null;
try {
    time = simpleDateFormat.parse(simpleDateFormat.format(timestamp));
} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Interval interval = new Interval(time.getTime(), now.getTime());
Period period = interval.toPeriod();

Integer s = period.getSeconds();
Integer m = period.getMinutes();
Integer h = period.getHours();
Integer days = period.getDays();

Integer mo = period.getMonths();
Integer y = period.getYears();

Integer mo = period.getMonths(); 始终为零

i/p=> now =Tue Oct 18 12:15:50 IST 2016
      time=Mon Sep 26 14:38:36 IST 2016

o/p=> s=14
      m=37
      h=21
      days=0
      mo=0
      y=0

我也尝试了 LocalDateDateTime 但遇到了同样的问题。

按照您现在的操作方式,您会得到一个以周为单位的周期。 period的'weeks'字段会被设置,years/months/days字段不会被设置

如果你想要一个包含年、月、日和时间的周期,那么你需要在区间上调用toPeriod时指定周期类型:

Period period = interval.toPeriod(PeriodType.yearMonthDayTime());

结果:

i/p=> now =Tue Oct 18 12:15:50 IST 2016
      time=Mon Sep 26 14:38:36 IST 2016

o/p=> s=14
      m=37
      h=21
      days=21
      mo=0
      y=0

当然,这个例子中的月和年字段仍然为 0,因为这两个日期相隔不到一个月。