两个Calendar对象的小时数差异 [英] Difference in hours of two Calendar objects

查看:200
本文介绍了两个Calendar对象的小时数差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆