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
我也试过LocalDate
和DateTime
但有同样的问题。
'simpleDateFormat.parse(simpleDateFormat.format(x))'是什么点? – Andreas
你的约会距离不到一个月,所以你几个月得到'0'这个事实并不令人惊讶。但是,天应该不为零。如果您使用Java 8,则会有一个新的内置日期/时间库(由执行JodaTime的人员创建),其中包括一个新的格式化程序/解析器。 –
因为是3周,所以你得到了0天。 'period.getWeeks()'返回3.您可以很容易地找到与我一样的方式,只需打印期间:'P3WT21H37M14S' – Andreas