两个 Calendar 对象的小时差
Difference in hours of two Calendar objects
我有两个 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 2015
而 c2.getTime()
是 Sun Feb 22 20:00:00 CET 2015
。
那么有没有任何代码可以 return 第一和第二 Calendar
之间的小时数差异?就我而言,它应该 return 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 8 你可以做到
long hours = ChronoUnit.HOURS.between(c1.toInstant(), c2.toInstant());
我有两个 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 2015
而 c2.getTime()
是 Sun Feb 22 20:00:00 CET 2015
。
那么有没有任何代码可以 return 第一和第二 Calendar
之间的小时数差异?就我而言,它应该 return 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 8 你可以做到
long hours = ChronoUnit.HOURS.between(c1.toInstant(), c2.toInstant());