我试着计算几个小时前,几分钟前,几个月前.
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,但也有同样的问题。
发布于 2016-10-18 07:25:22
按照你现在的做法,你会得到一个以星期为单位的句号。将设置期间的“周”字段,但不设置“年份/月/日”字段。
如果您想要一个具有年数、月、日和时间的期间,那么当您在间隔上调用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,因为这两个日期相隔不到一个月。
https://stackoverflow.com/questions/40101506
复制相似问题