SimpleDateFormat incorrectly parsing string

2019-07-22 11:59发布

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.

2条回答
小情绪 Triste *
2楼-- · 2019-07-22 12:21

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.

查看更多
3楼-- · 2019-07-22 12:43

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
查看更多
登录 后发表回答