I am trying to calculate the difference between two hours. Time format must be hh:mm:ss! I implement this code:
public static String timeDifference(long timeDifference1) {
long timeDifference = timeDifference1 / 1000;
int h = (int) (timeDifference / (3600));
int m = (int) ((timeDifference - (h * 3600)) / 60);
int s = (int) (timeDifference - (h * 3600) - m * 60);
return String.format("%02d:%02d:%02d", h, m, s);
}
public static void main(String[] args) throws ParseException {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String timeStart = sc.next();
String timeStop = sc.next();
char lol[]=timeStop.toCharArray();
if(lol[0]=='0' && lol[1]=='0'){
lol[0]='2';
lol[1]='4';
}
String tetx=String.valueOf(lol);
timeStop=tetx;
char kk[]=timeStart.toCharArray();
if(kk[0]=='0' && kk[1]=='0'){
kk[0]='2';
kk[1]='4';
}
String hhh=String.valueOf(kk);
timeStart=hhh;
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss");
Date d1 = null;
Date d2 = null;
d1 = format.parse(timeStart);
d2 = format.parse(timeStop);
long diff;
if (d1.getTime() > d2.getTime()) {
diff = (int) (d1.getTime() - d2.getTime());
} else
diff = (int) (d2.getTime() - d1.getTime());
System.out.println(timeDifference(diff));
}
}
Input must be:
10:03:43 15:00:58
13:00:00 14:00:00
00:00:00 12:05:00
12:05:00 00:00:00
And output:
04:57:15
01:00:00
12:05:00
11:55:00
But i get
04:57:15
01:00:00
00:05:00
00:05:00
How can i fix this?