Java 将毫秒格式化为简单日期格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6540380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Format milliseconds to simpledate format
提问by user706058
I'm facing a weird result when formatting milliseconds to a SimpleDate format:
将毫秒格式化为 SimpleDate 格式时,我遇到了一个奇怪的结果:
Output is:
输出是:
Start date time: 11/06/30 09:45:48:970
End date time: 11/06/30 09:45:52:831
Execution time: 01:00:03:861
Script:
脚本:
long dateTimeStart = System.currentTimeMillis();
// some script execution here
long dateTimeEnd = System.currentTimeMillis();
"Start date time: " + GlobalUtilities.getDate(dateTimeStart, "yy/MM/dd hh:mm:ss:SSS");
"End date time: " + GlobalUtilities.getDate(dateTimeEnd, "yy/MM/dd hh:mm:ss:SSS");
"Execution time: " + GlobalUtilities.getDate((dateTimeEnd - dateTimeStart), "hh:mm:ss:SSS");
Method:
方法:
public static String getDate(long milliseconds, String format)
{
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(milliseconds);
}
Any idea why the execution time value is so off? It should be 00:00:03:861, not 01:00:03:861
知道为什么执行时间值如此之低吗?应该是 00:00:03:861,而不是 01:00:03:861
Thanks
谢谢
采纳答案by Daniel Lundmark
The execution time is off because the Date constructor takes a long specifying the number of milliseconds since 1970-01-01.
执行时间关闭,因为 Date 构造函数需要很长时间来指定自 1970-01-01 以来的毫秒数。
回答by belgther
because you convert the time difference into the date. In detail, this is exactly what it happens:
因为您将时差转换为日期。详细地说,这正是它发生的事情:
- SimpleDateFormat.format(long milliseconds) calculates the date : Unix Birth Time + milliseconds.
- This time is also adjusted with the time difference from GMT.
- With these two informations, you get the weird result. To verify the information above, you can add day, month and year to the date.
- SimpleDateFormat.format(long milliseconds) 计算日期:Unix 出生时间 + 毫秒。
- 该时间也根据与 GMT 的时差进行调整。
- 有了这两个信息,你会得到奇怪的结果。要验证上述信息,您可以在日期中添加日、月和年。
Unfortunately, you can fix it by manually converting your time.
不幸的是,您可以通过手动转换时间来修复它。