What is the best way to deal with the NSDateFormatter locale “feechur”?

后端 未结 4 1955
花落未央
花落未央 2020-11-21 05:38

It seems that NSDateFormatter has a \"feature\" that bites you unexpectedly: If you do a simple \"fixed\" format operation such as:

NSDateForma         


        
4条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-21 06:14

    Instead of subclassing, you could create an NSDateFormatter category with an additional initializer that takes care of assigning the locale and possibly also a format string, so you'd have a ready-to-use formatter right after initializing it.

    @interface NSDateFormatter (LocaleAdditions)
    
    - (id)initWithPOSIXLocaleAndFormat:(NSString *)formatString;
    
    @end
    
    @implementation NSDateFormatter (LocaleAdditions)
    
    - (id)initWithPOSIXLocaleAndFormat:(NSString *)formatString {
        self = [super init];
        if (self) {
            NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
            [self setLocale:locale];
            [locale release];
            [self setFormat:formatString];
        }
        return self;
    }
    
    @end
    

    Then you could use NSDateFormatter anywhere in your code with just:

    NSDateFormatter* fmt = [[NSDateFormatter alloc] initWithPOSIXLocaleAndFormat:@"yyyyMMddHHmmss"];
    

    You might want to prefix your category method somehow to avoid name conflicts, just in case Apple decides to add such a method in a future version of the OS.

    In case you're always using the same date format(s), you could also add category methods that return singleton instances with certain configurations (something like +sharedRFC3339DateFormatter). Be aware however that NSDateFormatter is not thread-safe and you have to use locks or @synchronized blocks when you're using the same instance from multiple threads.

提交回复
热议问题