SimpleDateFormat timezone bug on Android

前端 未结 4 1004
你的背包
你的背包 2020-12-17 21:20

I\'ve been trying to isolate a bug in my application. I succeeded in producing the following \"riddle\":

SimpleDat         


        
相关标签:
4条回答
  • 2020-12-17 21:39

    I tried to compare s1 and s2 by running the same program. they come equal to me. enter image description here

    0 讨论(0)
  • 2020-12-17 21:42

    This is mentioned in javadoc of DateFormat#parse():

    Parse a date/time string according to the given parse position. For example, a time text "07/10/96 4:5 PM, PDT" will be parsed into a Date that is equivalent to Date(837039900000L).

    By default, parsing is lenient: If the input is not in the form used by this object's format method but can still be parsed as a date, then the parse succeeds. Clients may insist on strict adherence to the format by calling setLenient(false).

    This parsing operation uses the calendar to produce a Date. As a result, the calendar's date-time fields and the TimeZone value may have been overwritten, depending on subclass implementations. Any TimeZone value that has previously been set by a call to setTimeZone may need to be restored for further operations.

    Note the last paragraph. It unfortunately doesn't explain when exactly this will occur. To fix your particular problem you need to explicitly set the desired timezone before the formatting operation.

    As to the mutability of SimpleDateFormat itself, this is known for years. You should never create and assign an instance of it as a static or class variable, but always as a method (threadlocal) variable.

    0 讨论(0)
  • 2020-12-17 21:43

    Your question intrigued me so I went ahead and compiled your code. The result? As expected...

    2011-12-31T18:00:00+0100
    2011-12-31T18:00:00+0100
    

    The two values are the same, are you using some concurrency? Maybe the variable gets changed on another thread right before the f2.format(d).

    0 讨论(0)
  • 2020-12-17 21:44

    This is due to a bug in Android 2.1 (API 7). It seems that Android programmers missed some undocumented Java behavior (which is classified as an unfixable bug itself!) in their implementation of Android 2.1.

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