joda time period.getMonths()始终为0

时间:2016-10-18 06:55:50

标签: java jodatime

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

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,但遇到了同样的问题。

1 个答案:

答案 0 :(得分:2)

按照你现在的方式,你会得到一个以周为单位的句号。将设置期间的“周”字段,但不会设置年/月/日字段。

如果您想要一个包含年,月,日和时间的句点,则需要在间隔时调用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,因为这两个日期相隔不到一个月。