SimpleDateFormat incorrectly parsing string

拟墨画扇 提交于 2019-12-11 03:32:32

问题


String s = 19.17.38.008000;
DateFormat f = new SimpleDateFormat("HH.mm.ss.SSSSSS");
Date d = f.parse(s);
system.out.println(d);

this is the code I am running it runs fine except when it prints it prints the time 19:17:46. Please someone explain this to me

As a side note:

String s = 19.17.38.008000;
DateFormat f = new SimpleDateFormat("HH.mm.ss");
Date d = f.parse(s);
system.out.println(d);

this code will print the same string correctly minus the milliseconds. Someone please tell me what I am missing here.

EDIT: Thanks for the answers I think the issue here is I was reading 38.008000 as .008 seconds but sdf is reading SSS as 8000 milliseconds which are not the same thing.


回答1:


SSSSSS is still milli-seconds even if you put 6 of them. 19:17:38 + 008000 ms is 19:17:46 so it correct, if surprising.

AFAIK The java.time library in Java 8 supports micro-second (and nano-second) timestamps.

Thank you @Meno for the corrections.




回答2:


The SimpleDateFormat class is interpreting 008000 as 8000 milliseconds, or 8 seconds, and adding it to the 38 seconds already interpreted.

If we had this:

String s = "19.17.38.009000";

Then we would get this output, with 9 seconds added:

Thu Jan 01 19:17:47 PST 1970

Remove the 3 extra zeroes from the end of the string. If there are 6 digits, then they look like they should represent microseconds (millionths of a second), not milliseconds (thousandths of a second).

String s = "19.17.38.008";

Output:

Thu Jan 01 19:17:38 PST 1970


来源:https://stackoverflow.com/questions/23279619/simpledateformat-incorrectly-parsing-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!