运行以下代码:
private static String formatDuration(final long duration) {
final long hh = duration / 1000 / 3600;
final long mm = duration / 1000 % 3600 / 60;
final long ss = duration / 1000 % 3600 % 60;
return hh + "h" + ":" + mm + "m" + ":" + ss + "s";
}
private static void printDuartion() throws ParseException{
SimpleDateFormat PARSE_FORMAT = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
long dayFrom = PARSE_FORMAT.parse("11/02/2014 00:00:00").getTime();
long dayTo = PARSE_FORMAT.parse("11/03/2014 23:59:59").getTime();
System.out.println(formatDuration(dayTo-dayFrom));
}
我有一个输出: 48小时:59米:59S
但实际上它应该是: 47H:59米:59S
请帮我找出错误的位置。
答案 0 :(得分:3)
您的代码是正确的,我也得到47h:59m:59s
。演示:http://ideone.com/fxZKba
我只能想象你所处的时区受Daylight saving time的影响。像下面的例子中的“大西洋/百慕大”:
private static void printDuration() throws Exception {
SimpleDateFormat PARSE_FORMAT = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
PARSE_FORMAT.setTimeZone(TimeZone.getTimeZone("Atlantic/Bermuda"));
long dayFrom = PARSE_FORMAT.parse("11/02/2014 00:00:00").getTime();
long dayTo = PARSE_FORMAT.parse("11/03/2014 23:59:59").getTime();
System.out.println(formatDuration(dayTo - dayFrom));
}
在这种情况下,我得到48h:59m:59s
演示:http://ideone.com/jQ7sX2