Reputation: 11
In my code, I am generating timestamps value that is long millisecond .I want to convert this to HH:mm:ss(600000 to 00:10:00),I want disply difference in hh:mm:ss format
String strstart = "8:30:00";
String strend = "8:40:00";
SimpleDateFormat sdf1 = new SimpleDateFormat("hh:mm:ss");
try {
Date date1 = sdf1.parse(strstart);
Date date2 = sdf1.parse(strend);
long durationInMillis = date2.getTime() - date1.getTime();
System.out.println("durationInMillis---->" + durationInMillis);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I use bellow code and the output is 0:10:0
like this but i want the output like 00:10:00
int seconds = (int) (durationInMillis / 1000) % 60 ;
int minutes = (int) ((durationInMillis / (1000*60)) % 60);
int hours = (int) ((durationInMillis / (1000*60*60)) % 24);
System.out.println(hours+":"+minutes+":"+seconds);
Upvotes: 0
Views: 2245
Reputation: 4369
Another solution:
sdf1.setTimeZone(TimeZone.getTimeZone("etc/UTC"));
System.out.println(sdf1.format(new Date(durationInMillis)));
Upvotes: 0
Reputation: 12924
If you want to printf
you can use the same as mentioned by Joop Eggen. If you want to store the same in another string you can use as below.
String output = String.format("%02d:%02d:%02d%n", hours, minutes, seconds);
Upvotes: 0
Reputation: 109547
System.out.printf("%02d:%02d:%02d%n", hours, minutes, seconds);
By the way, use "HH:mm:ss"
as h
is for the 12 hour format (AM/PM) and H
for the 24 hour format - an interesting bug,
Upvotes: 2