0

在我的应用程序中,我使用 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];

问题是:如何调整上述所有内容的日期格式?有什么功能还是我应该手动执行?

提前致谢!

4

1 回答 1

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);
于 2013-04-17T11:41:21.117 回答