Incorrect parsing of date strings in SimpleDateFormat

前端 未结 1 1980
死守一世寂寞
死守一世寂寞 2020-12-11 19:55

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 f         


        
相关标签:
1条回答
  • 2020-12-11 20:24

    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.)

    0 讨论(0)
提交回复
热议问题