Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java中hh:mm:ss格式的时间毫秒_Java_Time - Fatal编程技术网

java中hh:mm:ss格式的时间毫秒

java中hh:mm:ss格式的时间毫秒,java,time,Java,Time,在我的代码中,我正在生成长毫秒的时间戳值。我想将其转换为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 =

在我的代码中,我正在生成长毫秒的时间戳值。我想将其转换为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);

顺便说一下,使用
“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)));

之所以会出现这种情况,是因为
int hours
值将存储为0而不是00。如果使用此代码意味着它不显示5:40:00,但我想要00:10:00,那么请跟随此帖子,我想要的是我想要差分时间,并添加到下一个时间,如9:30:00
sdf1.setTimeZone(TimeZone.getTimeZone("etc/UTC"));
System.out.println(sdf1.format(new Date(durationInMillis)));