Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate diff. between two times given that we have two different strings for time and date

Tags:

java

date

time

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.

  • time 1:"26/02/2011" and "11:00 AM"
  • time 2:"27/02/2011" and "12:15 AM"

Difference would be like 13 hours 15 minutes.

like image 346
user594720 Avatar asked Feb 27 '11 10:02

user594720


2 Answers

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.)

like image 125
tiago2014 Avatar answered Nov 13 '22 14:11

tiago2014


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
like image 8
Bala R Avatar answered Nov 13 '22 14:11

Bala R