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

后端 未结 5 386
闹比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

    /*
        x           number
        xx          two digit number
        xxx         abbreviated name
        xxxx        full name
    
        a           AM/PM
        A           millisecond of day
        c           day of week (c,cc,ccc,cccc)
        d           day of month
        e           day of week (e,EEE,EEEE)
        F           week of month
        g           julian day (since 1/1/4713 BC)
        G           era designator (G=GGG,GGGG)
        h           hour (1-12, zero padded)
        H           hour (0-23, zero padded)
        L           month of year (L,LL,LLL,LLLL)
        m           minute of hour (0-59, zero padded)
        M           month of year (M,MM,MMM,MMMM)
        Q           quarter of year (Q,QQ,QQQ,QQQQ)
        s           seconds of minute (0-59, zero padded)
        S           fraction of second
        u           zero padded year
        v           general timezone (v=vvv,vvvv)
        w           week of year (0-53, zero padded)
        y           year (y,yy,yyyy)
        z           specific timezone (z=zzz,zzzz)
        Z           timezone offset +0000
    
        sql         y-M-d H:m:s
        rss         [E, ]d MMM y[y] H:m:s Z|z[zzz]
    */
    

    This is my comment for date parsing. I use the following, where toDateUsingFormat uses an NSDateFormatter with the passed in string. I do not use a locale, because rss dates are not localized.

        if ( 0 == [string rangeOfString:@","].length ) {
            result = [string toDateUsingFormat:@"d MMM y H:m:s z"];
        } else {
            result = [string toDateUsingFormat:@"E, d MMM y H:m:s z"];
        }
    

    Edit:

    I use getObjectValue: instead of dateFromString.

    NSDate *result = nil;
    NSError *error = nil;
    [dataFormatter getObjectValue:&result forString:dateString errorDescription:&error];
    

提交回复
热议问题