问题描述
我正在尝试将UTC中的字符串格式化日期转换为日期对象,该对象将导致关闭几分钟的转换。
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"));
解析日期字符串之前是 - 2014-07-07T18:24: 23.788810
Before Parsing the date string is - 2014-07-07T18:24:23.788810
解析日期后 Tue Jul 08 00:07:31 GMT + 05:30 2014
After Parsing the Date is Tue Jul 08 00:07:31 GMT+05:30 2014
正确的日期转换为 Tue Jul 07 23:54:23 GMT + 05:30 2014
转化中约有12-13分钟的差异。我观察到转换中10分钟范围内的差异。
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?
推荐答案
SSSSSS
正在解析数毫秒,而不是你所期待的毫秒。
SSSSSS
is parsing a number of milliseconds - not microseconds, as you're expecting.
788810毫秒是13分8秒810毫秒。所以你的结果实际上是2014-07-07T18:27:31.810。
788810 milliseconds is 13 minutes, 8 seconds and 810 milliseconds. So your result is actually 2014-07-07T18:27:31.810.
是的,这是一个非常愚蠢的API设计。这将使更有意义的是 S ... S
表示几分之一而不是毫秒 - 但它远离关于Java-8之前的日期/时间API最糟糕的事情:(
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 :(
我不认为有一种方法来解析微秒 SimpleDateFormat
- Java时间API前Java-8的精度无论如何都是毫秒 - 所以我想你只需要用 substring
,并使用格式字符串末尾的 SSS
进行解析。
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.
如果您使用Java 8,我强烈建议您接受 java.time
,我相信可以处理这种情况(我没看过在解析API,但我确定这将是罚款。)
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.)
这篇关于SimpleDateFormat中日期字符串解析不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!