-3

I have to find the difference in time between two different date i try this:

Date d1 = null;
Date d2 = null;
d1 = format.parse(startDate);
d2 = format.parse(endDate);

long diff = d2.getTime() - d1.getTime();

diffSeconds = diff / 1000 % 60;          
diffMinutes = diff / (60 * 1000) % 60;         
diffHours = diff / (60 * 60 * 1000);

but when i set startDate to 15/05/2017 23:40:10 andendDate to 16/05/2017 00:05:55

the output is:

diffSeconds = -15;
diffMinutes = -25;
diffHours   = -23;

how i can fix this? thank you.

senerh
  • 1,315
  • 10
  • 20
MFaouzi
  • 1
  • 1

1 Answers1

0

Either you made a mistake in the date format, or you've switched the start and end dates.

The following works perfectly fine:

SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");

String startDate = "15/05/2017 23:40:10";
String endDate = "16/05/2017 00:05:55";

Date d1 = format.parse(startDate);
Date d2 = format.parse(endDate);

long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000);

System.out.println(diffHours + " " + diffMinutes + " " + diffSeconds);

Output is:

0 25 45
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156