0

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);
Jayamohan
  • 12,734
  • 2
  • 27
  • 41
user1935977
  • 11
  • 1
  • 4
  • You are getting that because `int hours` value would be stored as 0 instead of 00. Instead of this follow this post [Link](http://stackoverflow.com/questions/8237193/java-convert-milliseconds-to-date) – Shiva Komuravelly Jan 05 '13 at 08:06

3 Answers3

2
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,

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
0

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);
Jayamohan
  • 12,734
  • 2
  • 27
  • 41
0

Another solution:

sdf1.setTimeZone(TimeZone.getTimeZone("etc/UTC"));
System.out.println(sdf1.format(new Date(durationInMillis)));
Donato Szilagyi
  • 4,279
  • 4
  • 36
  • 53
  • if use this code means its not showing 5:40:00 like but i want 00:10:00,what i want means I want difference time and add to next time like 9:30:00 – user1935977 Jan 05 '13 at 09:24