2016-10-18 48 views
0

我试图计算日期之间的差异,比如天前,分钟前,两个月前,...乔达时间period.getMonths()始终为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但有同样的问题。

+3

'simpleDateFormat.parse(simpleDateFormat.format(x))'是什么点? – Andreas

+1

你的约会距离不到一个月,所以你几个月得到'0'这个事实并不令人惊讶。但是,天应该不为零。如果您使用Java 8,则会有一个新的内置日期/时间库(由执行JodaTime的人员创建),其中包括一个新的格式化程序/解析器。 –

+0

因为是3周,所以你得到了0天。 'period.getWeeks()'返回3.您可以很容易地找到与我一样的方式,只需打印期间:'P3WT21H37M14S' – Andreas

回答

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,因为这两个日期间隔不到一个月。