user5810842
user5810842

Reputation:

Getting difference between two Timestamp objects in Java

I'm working on a project, it's about parking and it contains a database. I have variable timestamp for time/date when car enter the parking, and one also for when the car is on the exit. I want to get difference in hours (minute after every full hour is a new hour etc. 4 hours and 2 mins are same as 5 hours) so I can calculate price of the service (hours multiply by price per hour).

Help me pls, and thank you in advance

Upvotes: 0

Views: 690

Answers (2)

Austin
Austin

Reputation: 8575

After obtaining the time value in milliseconds (e.g. using a Date object) use TimeUnit to get the difference in times:

TimeUnit.HOURS.convert(timeOut.getTime()-timeIn.getTime(), TimeUnit.MILLISECONDS);

Upvotes: 0

Suresh Reddy Guntaka
Suresh Reddy Guntaka

Reputation: 849

get difference in milliseconds and calculate as below

long timeDiff = endTime.getTime() - startTime.getTime()

int hours = (int)Math.ceil(timeDiff/1000*60*60) //In here we are converting milli seconds difference to hours and then if it is not an exact number we are converting that to the next integer

Upvotes: 1

Related Questions