Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

java - Incorrect parsing of date strings in SimpleDateFormat

I'm trying to convert a string formatted date in UTC to a date object which is resulting a conversion that is off by a couple of minutes.

SimpleDateFormat fullDateFormater = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSS", Locale.US);
fullDateFormater.setTimeZone(TimeZone.getTimeZone("UTC"));

Before Parsing the date string is - 2014-07-07T18:24:23.788810

After Parsing the Date is Tue Jul 08 00:07:31 GMT+05:30 2014

The correct date conversion is Tue Jul 07 23:54:23 GMT+05:30 2014

There is a difference of about 12-13 minutes in the conversion. I have observed a difference in the range of 10 minutes in the conversion.

Any idea what is going wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

SSSSSS is parsing a number of milliseconds - not microseconds, as you're expecting.

788810 milliseconds is 13 minutes, 8 seconds and 810 milliseconds. So your result is actually 2014-07-07T18:27:31.810.

Yes, this is a really stupid bit of API design. It would make much more sense for S...S to mean "fractions of a second" instead of "milliseconds" - but it's far from the worst thing about the pre-Java-8 date/time API :(

I don't think there's a way to parse microseconds with SimpleDateFormat - the precision of Java time APIs pre-Java-8 is milliseconds anyway - so I think you'll just need to chop off the last three digits with substring and parse it using SSS at the end of your format string.

If you're using Java 8, I'd strongly encourage you to embrace java.time, which I'm sure can handle this situation. (I haven't looked at its parsing API, but I'm sure it'll be fine.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...