The difference in hours of two Calendar objects

I have two objects Calendar, and I want to check what is the difference between them, in hours.

Here is the first Calendar

Calendar c1 = Calendar.getInstance();

And second 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"));

Now let's say that c1.getTime(): Fri Feb 20 20:00:00 CET 2015it c2.getTime()is Sun Feb 22 20:00:00 CET 2015.

So is there any code that returns the difference between the first and second Calendarin the watch? In my case, he should be back 48.

+4
source share
2 answers

You can try the following:

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

Or using the Joda-Time API Period, you can use the constructor public Period(long startInstant, long endInstant)and get the clock field:

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

In Java 8 you can do

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

All Articles