两个Calendar对象的小时数差异 [英] Difference in hours of two Calendar objects
问题描述
我有两个 Calendar
对象,我想检查它们之间的小时数差异。
I have two Calendar
objects, and I want to check what is the difference between them, in hours.
这里是第一个日历
Calendar c1 = Calendar.getInstance();
第二个日历
Calendar c2 = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
c2.setTime(sdf.parse("Sun Feb 22 20:00:00 CET 2015"));
现在让我们说 c1.getTime()
是: 2015年2月20日星期五20:00:00
和 c2.getTime()
是 Sun Feb 22 20:00:00 CET 2015
。
Now lets say that c1.getTime()
is: Fri Feb 20 20:00:00 CET 2015
and c2.getTime()
is Sun Feb 22 20:00:00 CET 2015
.
那么是否有任何代码可以返回第一个和第二个之间的差异日历
小时?就我而言,它应该返回 48
。
So is there any code that would return the difference between first and second Calendar
in hours? In my case it should return 48
.
推荐答案
您可以尝试以下:
long seconds = (c2.getTimeInMillis() - c1.getTimeInMillis()) / 1000;
int hours = (int) (seconds / 3600);
或者使用Joda-Time API的 Period
类,则可以使用构造函数 public Period(long startInstant,long endInstant)
并检索小时字段:
Or using the Joda-Time API's Period
class, you can use the constructor public Period(long startInstant, long endInstant)
and retrieve the hours field:
Period period = new Period(c1.getTimeInMillis(), c2.getTimeInMillis());
int hours = period.getHours();
这篇关于两个Calendar对象的小时数差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!