What's wrong with how I'm using NSDateFormatter?

后端 未结 5 414
闹比i
闹比i 2021-01-30 10:01
   NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
   dateFormatter.locale = [[[NSLocale alloc] initWithLocaleIdentifier:@\"en_US\"] autorelease];
   [d         


        
5条回答
  •  走了就别回头了
    2021-01-30 10:19

    The answer to this question is the following: I was using the wrong date format string:

    @"EEE, d MMM yyyy HH:mm:ss zzz"
    

    when it should have been:

    @"EEE, dd MMM y HH:mm:ss zzz"
    

    The part about iOS 4 and NDA was that I thought I had to use the NSDateFormatter method dateFormatFromTemplate:options:locale: which would have looked like this:

    NSString *format = [NSDateFormatter dateFormatFromTemplate:@"EEE, d MMM yyyy HH:mm:ss zzz" options:0 locale:[NSLocale currentLocale]];
    

    However, that method should only be used when you want to DISPLAY the date to a user of unknown locale. In my case, I knew exactly what the date format was going to look like and I was trying to PARSE the date string so that I could store it in CoreData. Therefore, that method wasn't useful.

    Bonus bookmark: Read this table very carefully and you will definitely figure out what the problem is... Unicode date formats should follow these specifications: http://unicode.org/reports/tr35/tr35-6.html#Date_Field_Symbol_Table

    TL;DR The format string was wrong. D'oh!

提交回复
热议问题