java - 两个 Calendar 对象的小时差

标签 java android calendar simpledateformat

我有两个 Calendar 对象,我想检查它们之间的区别,以小时为单位。

这是第一个日历

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() 是:Fri Feb 20 20:00:00 CET 2015c2.getTime()Sun Feb 22 20:00:00 CET 2015

那么是否有任何代码可以返回第一个和第二个 Calendar 之间的小时差?在我的例子中,它应该返回 48

最佳答案

您可以尝试以下方法:

long seconds = (c2.getTimeInMillis() - c1.getTimeInMillis()) / 1000;
int hours = (int) (seconds / 3600);

或者使用 Joda-Time API 的 Period class ,您可以使用构造函数 public Period(long startInstant, long endInstant) 并检索小时字段:

Period period = new Period(c1.getTimeInMillis(), c2.getTimeInMillis());
int hours = period.getHours();

关于java - 两个 Calendar 对象的小时差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28651107/

相关文章:

java - 使用 Runtime 从 Java 运行 Maven 命令

java - 错误 : Entities and Pojos must have a usable public constructor.

java - activemq 和 Glassfish : InactivityIOException: Channel was inactive for too long

java - 递归获取NodeAt java

javascript - 需要帮助在日语中格式化 MomentJS 中的日期

java - 带有 Android 的 Google Cloud Endpoints - 缓存响应?

android - Android 中带复选框的多级 ExpandableListView

android - 在使用 tensorflow 模型时,我们可以使用 .pbtxt 而不是 .pb 文件吗

java - 用于检查事件发生的时间容器

android - 如何启动Android日历应用程序低于4.0(IceCream)?