具有T-Z时间格式的NSDateFormatter

时间:2016-02-01 14:32:54

标签: ios objective-c google-api

我收到了T-Z格式的字符串,例如" 2015-12-12T05:30:03.634Z"来自Google服务器。如何将其转换为"YYYY-MM-dd HH:mm:ss"格式NSDateFormat

我已尝试过以下代码,但总是在变量dte中得到(null)。

+(NSDate*)tzStrToDateTime:(NSString*)tzStr{
  NSLog(@"Convert tzStr: %@ ",tzStr);
  NSString *tzFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSX";//2015-12-12T05:30:03.634Z
  NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
  [dateFormat setDateFormat:tzFormat];
  [dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"Asia/Taipei"]];
  NSDate *dte = [dateFormat dateFromString:tzStr];
  NSLog(@"to Date: %@", dte);
  return dte;
}

1 个答案:

答案 0 :(得分:4)

初始dateFormat就像

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat: @"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
[dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"Asia/Taipei"]];
NSDate *dte = [dateFormat dateFromString:@"2015-12-12T05:30:03.634Z"];
//Second Conversion
 [dateFormat setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
 NSString *finalStr = [dateFormat StringFromdate:dte];