【问题标题】:Difference in hours of two Calendar objects两个日历对象的小时差
【发布时间】:2015-02-21 20:42:33
【问题描述】:

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

这是第一个Calendar

Calendar c1 = Calendar.getInstance();

还有第二个Calendar

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

【问题讨论】:

  • 如果可能,使用 JodaTime 或 Java 8 的 Time API

标签: java android calendar simpledateformat


【解决方案1】:

您可以尝试以下方法:

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.time.Period 在 Android 中需要 API 26。
【解决方案2】:

在 Java 8 中你可以这样做

long hours = ChronoUnit.HOURS.between(c1.toInstant(), c2.toInstant());

【讨论】:

  • java.time.temporal.ChronoUnit 在 Android 中需要 API 26。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-03
  • 1970-01-01
  • 2013-10-14
  • 1970-01-01
  • 2016-02-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多