Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in hours of two Calendar objects

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

Here is the first Calendar

Calendar c1 = Calendar.getInstance();

And the 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 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.

So is there any code that would return the difference between first and second Calendar in hours? In my case it should return 48.

like image 482
Enve Avatar asked Feb 21 '15 20:02

Enve


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'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();
like image 192
M A Avatar answered Sep 19 '22 07:09

M A


In Java 8 you could do

long hours = ChronoUnit.HOURS.between(c1.toInstant(), c2.toInstant());
like image 35
Reimeus Avatar answered Sep 19 '22 07:09

Reimeus