问题描述
我想解析时间戳,如下所示 - 2016-03-16 01:14:21.6739
。但是当我使用 SimpleDateFormat
来解析它时,我发现它输出了一个不正确的解析值。它将隐藏6739毫秒到6秒,剩下739毫秒。它将日期转换为此格式 - Wed Mar 16 01:14:27 PDT 2016
。为什么秒部分从21秒变为27秒(增加6秒?)。以下是我的代码片段:
I want to parse a timestamp, like this - "2016-03-16 01:14:21.6739"
. But when I use the SimpleDateFormat
to parse it, I find that it outputs an incorrect parsed value. It will covert 6739 milliseconds to 6 seconds with 739 millseconds left. It converted the date to this format - Wed Mar 16 01:14:27 PDT 2016
. Why the seconds part has changed from 21 seconds to 27 seconds(an addition of 6 seconds?). The following is my code snippet:
final SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSS");
String parsedate="2016-03-16 01:14:21.6739";
try {
Date outputdate = sf.parse(parsedate);
String newdate = outputdate.toString(); //==output date is: Wed Mar 16 01:14:27 PDT 2016
System.out.println(newdate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
推荐答案
似乎不可能使用SimpleDateFormat以比毫秒更精细的粒度表达时间。
发生的事情是,当你输入6739时,Java将其理解为6739毫秒,即6秒和739毫秒,因此观察到6秒的差异。
It seems that is not possible to use SimpleDateFormat to express times with a finer grain than the millisecond.What is happening is that as you put 6739, Java understands it as 6739 milliseconds i.e. 6 seconds and 739 milliseconds hence the 6 seconds difference observed.
检查这些其中,它解释得很好:
Check these ones, it is explained quite well: String-Date conversion with nanoseconds Java date parsing with microsecond or nanosecond accuracy
这篇关于SimpleDateFormat无法解析超过4位数的毫秒数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!