Timemillisecond to hh:mm:java中的ss格式

在我的代码中,我生成的时间戳值为长毫秒。我想将其转换为HH:mm:ss(600000到00:10:00),我想要差异hh:mm:ss格式

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(); } 

我使用波纹管代码,输出为0:10:0但我希望输出像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); 

 System.out.printf("%02d:%02d:%02d%n", hours, minutes, seconds); 

顺便说一下,使用"HH:mm:ss"作为h表示12小时格式(AM / PM)和H表示24小时格式 – 这是一个有趣的错误,

如果你想printf你可以使用Joop Eggen提到的相同。 如果你想将它存储在另一个字符串中,你可以使用如下。

 String output = String.format("%02d:%02d:%02d%n", hours, minutes, seconds); 

另一种方案:

 sdf1.setTimeZone(TimeZone.getTimeZone("etc/UTC")); System.out.println(sdf1.format(new Date(durationInMillis)));