I want to calculate the difference between two date/time in java using Date and Calendar classes. The format that I have is \"2012-01-24 12:30:00 PM\".
I have implem
The reason why it shows 10 hours as the difference is that you've got an error in the pattern when parsing the input.
Here's an example using SimpleDateFormat:
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
Date date1 = df.parse("2012-01-24 12:30:00 PM");
Date date2 = df.parse("2012-01-24 02:30:00 PM");
long differenceInHours = Math.abs(date1.getTime() - date2.getTime()) / 1000 / 60 / 60);
Will return 10.
When we just slightly change the date format pattern, using hh for hour in am/pm (1-12) instead of HH for hour in day (0-23):
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");
It returns (the expected) 2.
See the documentation for SimpleDateFormat to get your patterns right.