NSDateFormatter will not parse string with timezone that includes colon

前端 未结 4 1056
心在旅途
心在旅途 2021-01-16 20:50

I\'m trying to transform @\"Fri, 26 Aug 2011 10:51:00 +02:00\" into an NSDate:

[dateFormatter setDateFormat:@\"EEE, dd MMM yyyy HH:         


        
4条回答
  •  礼貌的吻别
    2021-01-16 21:32

    The colon in the timezone (+02:00) is the issue. According to the Unicode Standard #35, 1..3 capital Z pattern denotes a RFC 822 time zone. RFC 822 time zones represent the offset from GMT (or UTC) and have the following format:

    zone             =  "UT"  / "GMT"                ; Universal Time
                     ...
                     ...
                     / ( ("+" / "-") 4DIGIT )        ; Local differential
                                                     ;  hours+min. (HHMM)
    

    As you can see, there is no colon between hours and minutes of the time zone. Therefore, the time zone should be +0200.

    The most proper solution would be to generate a unicode compliant date string in the first place, but if you are stuck with this format, you may need to preprocess the date string before you pass it to NSDateFormatter.

    For example, a quick fix would be using stringByReplacingOccurrencesOfString to get rid of the colon in the time zone:

    // dateString --> Fri, 26 Aug 2011 10:51:00 +02:00
    dateString = [dateString stringByReplacingOccurrencesOfString:@":" 
                                                       withString:@"" 
                                                          options:0
                                                            range:NSMakeRange(25, [dateString length] - 25)];
    // dateString --> Fri, 26 Aug 2011 10:51:00 +0200
    [dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss Z"];
    NSDate *date = [dateFormatter dateFromString:dateString];
    // date --> 2011-08-26 08:51:00 +0000
    

提交回复
热议问题