我如何将1990-12-31T23:59:60Z转换为NSDate

时间:2016-01-17 18:24:33

标签: ios objective-c iphone

我已经尝试了从c解决方案strptime_lNSDataDetectorNSDateFormatter的所有内容。 NSDataDetector返回

  

1990-12-31 11:00:00 +0000

但它不是一个好的价值,所以我应该如何将其转换为NSDate。 这是NSDataDetector解决方案:

NSString *myDateString = @"1990-12-31T23:59:60Z";
NSError *error = nil;
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeDate error:&error];
NSArray *matches = [detector matchesInString:myDateString options:0 range:NSMakeRange(0, [myDateString length])];
for (NSTextCheckingResult *match in matches) {
    NSLog(@"Detected Date: %@", match.date);           // => 2011-11-24 14:00:00 +0000
    NSLog(@"Detected Time Zone: %@", match.timeZone);  // => (null)
    NSLog(@"Detected Duration: %f", match.duration);   // => 0.000000
}

这是strptime_l解决方案。

struct tm  sometime;
const char *formatString = "%Y-%m-%d %H:%M:%S %z";
(void) strptime_l("1990-12-31T23:59:60Z", formatString, &sometime, NULL);
NSDate *cDate = [NSDate dateWithTimeIntervalSince1970: mktime(&sometime)];
NSLog(@"NSDate is %@", cDate);

而dateFormats是具有日期格式的数组,

    for (NSString *dateFormat in dateFormats) {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:dateFormat];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
    detectedDate = [dateFormatter dateFromString:[dictionary[@"date"] stringValue]];
    if (detectedDate != nil) {
        break;
    }
}

如果日期格式相等

@"yyyy-MM-dd'T'HH:mm:ssZ"

setDateFormat:dateFormat为我的值返回nil,但它适用于

  

1990-12-31T23:59:59

1 个答案:

答案 0 :(得分:0)

试试这个:

NSString * yourDate = @"1990-12-31T23:59:60Z";
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:SSZ"];
NSDate * date = [dateFormatter dateFromString:yourDate];
NSLog(@"%@", date);