NSDateFormatter for BST instead of GMT+1

后端 未结 2 468
情深已故
情深已故 2021-01-17 04:30

I want to display the following string on my time axis:

\"GMT/BST\"

Here\'s the code:

 NSDateFormatter *dateformatter=[[NSDateFormatter alloc         


        
相关标签:
2条回答
  • 2021-01-17 04:50

    I spent a day on this and wanted to make sure so others don't get hung up on it.

    For a UK region/locale, the 'z' field pattern in DateFormatter returns the proper string for the "America/London" timezone (e.g. "GMT" or "BST"). However, if you use the US region/locale, 'z' will give you "GMT+1".

    The gotcha happens when an abbreviation for the given target timezone with a given locale doesn't exist. I was using the 'v' field pattern, and with the US region, "Europe/London" was falling back to "United Kingdom Time", which blew up my text label. 'z' is better, it falls back to "GMT+1" while in DST, but still not the desired "BST".

    The abbreviationDictionary doesn't consider daylight savings time. It's meant to map an abbreviation to a timezone. You'll find "BST":"Americal/London", but this only applies while observing daylight savings time as mentioned by @Nick T. During standard time, Brits are used to seeing "GMT".

    Unfortunately, without recreating timezone functionality yourself, you're left with compromises. I think iOS can do better here.

    Reference

    • Date Field Symbol Table as part of the Unicode Technical Standard
    0 讨论(0)
  • 2021-01-17 04:58

    Turns out there is a built in array of 48 time zone abbreviations (e.g. 'BST') in iOS.

    NSDictionary *tzDict = [NSTimeZone abbreviationDictionary]; 
    

    There is an array of 419 time zone names in this array (e.g. 'Europe/London'):

    NSArray *timeZoneNames = [NSTimeZone knownTimeZoneNames];
    

    tzDict contains the abbreviations for daylight saving time for a subset of time zone names. So the algorithm would be to check if we are in DST, then see if tzDict has an entry, and subsitute that or if not, use

    [NSTimeZone abbreviation];
    

    Here are a few other topics on time zones in general.

    Daylight saving time and time zone best practices

    How can I map tz database names to city and country names?

    C# british summer time (BST) timezone abbreviation

    http://en.wikipedia.org/wiki/List_of_tz_database_time_zones

    GMT timezone conversion in objective c

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