iOS - 解析不同的日期格式

时间:2012-01-03 16:56:51

标签: iphone ios nsdate nsdateformatter

我是iOS新手。我希望将诸如“2012-01-02T00:00:00-05:00”之类的日期解析为“YYYY-MM-dd HH:mm:ss”格式。到目前为止,我已经完成了以下工作 -

NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
[inputFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
NSString *xExpDate = expirationDate;
NSString *tempExpDate = [xExpDate stringByReplacingOccurrencesOfString:@"T" withString:@" "];

在此之后我不知道该怎么做。有什么想法吗?

2 个答案:

答案 0 :(得分:3)

  NSString *d = @"2012-01-02T00:00:00-0500";

  NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
  [inputFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
  [inputFormatter setDateFormat:@"YYYY-MM-dd'T'HH:mm:ssZZZ"];
  NSDate *xExpDate = [inputFormatter dateFromString:d];
  NSLog(@"xExpDate: %@", xExpDate);

我认为您的日期字符串不正确,因为该区域应该没有任何“:”

答案 1 :(得分:1)

YYYY-MM-dd HH:mm:ss 更改为 yyyy-MM-dd HH:mm:ss

NSString *result = [inputFormatter dateFromString:expirationDate];

修改

NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
[inputFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
NSDate *date = [inputFormatter dateFromString:expirationDate];
NSLog(@"Actual Date: %@", date);

[inputFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *result = [inputFormatter stringFromDate:date];
[inputFormatter release];

NSLog(@"formatted Date: %@", result);

参考 dateFromString Unicode format