dateFrom String返回nil,日期时间的字符串为" Mon,2015年4月20日06:00:26 + 0000"

时间:2015-04-20 10:59:26

标签: ios objective-c nsdateformatter

- (void)viewDidLoad {
    [super viewDidLoad];

    self.dateTimeFormate = [[NSDateFormatter alloc] init];
    self.dateTimeFormate.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en-US"];
    [self.dateTimeFormate setDateFormat:@"mm-dd-YYYY hh:mm"];

}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    cell.textLabel.text = [[self.arrFeeds objectAtIndex:indexPath.row] objectForKey:@"title"];

    NSString *strPubDate = [[self.arrFeeds objectAtIndex:indexPath.row] objectForKey:@"pubDate"];
    NSString *strPubDateTrim = [strPubDate stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString *strCreator = [[self.arrFeeds objectAtIndex:indexPath.row] objectForKey:@"dc:creator"];
    NSString *strCreatorTrim = [strCreator stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

    NSDate *dateTime = [self.dateTimeFormate dateFromString:strPubDateTrim];
    NSString *strPubDateTime = [self.dateTimeFormate stringFromDate:dateTime];

    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ - %@",strPubDateTime,strCreatorTrim];

    return cell;
}
}

1 个答案:

答案 0 :(得分:1)

输入 Mon, 20 Apr 2015 06:00:26 +0000

NSString *str =@"Mon, 20 Apr 2015 06:00:26 +0000";
NSDateFormatter *sdateFormatter = [[NSDateFormatter alloc] init];
sdateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[sdateFormatter setDateFormat:@"E, dd MMM yyyy hh:mm:ss Z'"];

NSDate *sdate = [sdateFormatter dateFromString:str];
NSLog(@"%@",[sdateFormatter stringFromDate:sdate]);

输出: Mon, 20 Apr 2015 11:30:26 +0530
然后
输入 Mon, 20 Apr 2015 11:30:26 +0530 => sdate

NSDateFormatter *dateformate=[[NSDateFormatter alloc]init];
[dateformate setDateFormat:@"MM-dd-yyyy hh:mm a"];
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[dateformate setTimeZone:gmt];//add this
NSString *stringDate = [dateformate stringFromDate:sdate];
NSLog(@"%@",stringDate);

输出 04-20-2015 11:30 AM