在我的应用程序中使用NSXMLParser来解析提要。 我有一个pubDate,但有许多不同的字符串日期格式:
1. 2013-04-17T12:00:24
2. Wed, 17 Apr 2013 10:15 +0300
3. Wed, 17 Apr 2013 11:07:01 +0200
4. 11/04/2013 18:10:10
这是我的代码:
NSDateFormatter *inputFormatter = [[NSDateFormatter alloc]init];
assert(inputFormatter != nil);
NSLocale *loacle = [[NSLocale alloc]initWithLocaleIdentifier:@"en_US_POSIX"];
assert(loacle != nil);
[inputFormatter setLocale:loacle];
[inputFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss Z"];
[inputFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSString *dateString = [NSString stringWithFormat:@"%@",currentPubDate];
NSDate *inputDate = [inputFormatter dateFromString:dateString];
NSLocale *hebrow = [[NSLocale alloc]initWithLocaleIdentifier:@"he_IL"];
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc]init];
outputFormatter.locale = hebrow;
[outputFormatter setDateStyle:NSDateFormatterFullStyle];
[outputFormatter setTimeStyle:NSTimeZoneNameStyleShortStandard];
NSString *outputDate = [outputFormatter stringFromDate:inputDate];
问题是:如何调整上述所有日期格式? 有任何功能,还是我应该手动完成?
提前感谢!
答案 0 :(得分:1)
这不是一个理想的解决方案,但应该有效,因为dateString没有任何关于时区的信息是UTC。
NSString *dateString = @"11/04/2013 18:10:10";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
NSLocale *enUSPOSIX = [[NSLocale alloc]initWithLocaleIdentifier:@"en_US_POSIX"];
[dateFormatter setLocale:enUSPOSIX];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDate *date = nil;
NSError *error = nil;
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeDate
error:&error];
NSArray *matches = [detector matchesInString:dateString
options:0
range:NSMakeRange(0, [dateString length])];
for (NSTextCheckingResult *match in matches) {
if (match.date) {
date = match.date;
break;
}
}
if (!date) {
NSArray *dateFormats = @[@"yyyy-MM-dd'T'HH:mm:ss",
@"EEE, dd MMM yyyy HH:mm Z",
@"EEE, dd MMM yyyy HH:mm:ss Z",
@"dd/MM/yyyy HH:mm:ss"];
for (NSString *dateFormat in dateFormats) {
[dateFormatter setDateFormat:dateFormat];
date = [dateFormatter dateFromString:dateString];
if (date) {
break;
}
}
}
NSLocale *hebrowLocale = [[NSLocale alloc]initWithLocaleIdentifier:@"he_IL"];
[dateFormatter setLocale:hebrowLocale];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
[dateFormatter setDateStyle:NSDateFormatterFullStyle];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
NSString *formattedDateString = [dateFormatter stringFromDate:date];
NSLog(@"DateString : %@",formattedDateString);