my NSDateFormatter works only in the iPhone simulator

后端 未结 7 2086
独厮守ぢ
独厮守ぢ 2020-12-20 04:13

I use a NSDateFormatter which works fine in the simulator, but I get a nil when I run it in the iPhone. I hardcoded the date to be sure of the format, but it fails anyway. <

7条回答
  •  清酒与你
    2020-12-20 04:30

    I second Manuel Spuhler's advice of manually parsing - not my favorite option, but Objective-C's options for that are way too complicated (and lacking in error reporting - anything wrong just spits nil, without a hint on the error).

    One thing that worked for me is to use C's strptime to decouple the date, then reconstruct it as a NSDate object. For example, the code below tkes a string received as something like "Monday, 28-Sep-09 18:13:50 UTC" and converts it to a NSDate object adapting the UTC time for the local time:

        struct tm time;
        strptime([currentStringValue UTF8String], "%A, %d-%b-%y %H:%M:%S %z", &time);   
        NSDate* myDate = [NSDate dateWithString:
            [NSString stringWithFormat:@"%04d-%02d-%02d %02d:%02d:%02d +0000",
                time.tm_year+1900, time.tm_mon+1, time.tm_mday,
                time.tm_hour, time.tm_min, time.tm_sec]
        ];
    

    (could handle other zones by adding other struct tm parameters instead of the +0000 fixed time zone, see time.h entry on wikipedia for details):

提交回复
热议问题