I have time data split in two strings - one string for date, and one for time.
I want to calculate the diff. of such two times in Java.
e.g.
Difference would be like 13 hours 15 minutes.
String str_date1 = "26/02/2011";
String str_time1 = "11:00 AM";
String str_date2 = "27/02/2011";
String str_time2 = "12:15 AM" ;
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm a");
Date date1 = formatter.parse(str_date1 + " " + str_time1);
Date date2 = formatter.parse(str_date2 + " " + str_time2);
// Get msec from each, and subtract.
long diff = date2.getTime() - date1.getTime();
System.out.println("Difference In Days: " + (diff / (1000 * 60 * 60 * 24)));
Obs: This is only valid as an aproximation. See Losing Time on the Garden Path.)
try {
String date1 = "26/02/2011";
String time1 = "11:00 AM";
String date2 = "27/02/2011";
String time2 = "12:15 AM";
String format = "dd/MM/yyyy hh:mm a";
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date dateObj1 = sdf.parse(date1 + " " + time1);
Date dateObj2 = sdf.parse(date2 + " " + time2);
System.out.println(dateObj1);
System.out.println(dateObj2);
long diff = dateObj2.getTime() - dateObj1.getTime();
double diffInHours = diff / ((double) 1000 * 60 * 60);
System.out.println(diffInHours);
System.out.println("Hours " + (int)diffInHours);
System.out.println("Minutes " + (diffInHours - (int)diffInHours)*60 );
} catch (ParseException e) {
e.printStackTrace();
}
output
Sat Feb 26 11:00:00 EST 2011
Sun Feb 27 00:15:00 EST 2011
13.25
Hours 13
Minutes 15.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With