如何将带有时区的日期字符串转换为NSDate

时间:2012-05-13 09:14:46

标签: iphone objective-c nsdate

如何将日期字符串“2012-05-03 06:03:00 +0000”转换为NSDate。我使用下面的代码,但它不起作用:

NSDateFormatter *datFormatter = [[NSDateFormatter alloc] init];
[datFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
NSDate* date = [datFormatter dateFromString:dateStr];

2 个答案:

答案 0 :(得分:10)

  NSString *dateStr = @"2012-05-03 06:03:00 +0000";
  NSDateFormatter *datFormatter = [[NSDateFormatter alloc] init];
  [datFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
  NSDate* date = [datFormatter dateFromString:dateStr];
  NSLog(@"date: %@", [datFormatter stringFromDate:date]);

此代码打印date: 2012-05-03 09:03:00 +0300

有效。另外,不要忘记设置您要定位的日期格式化程序的时区

答案 1 :(得分:0)

可以这样做: -

NSDateFormatter *datFormat = [[NSDateFormatter alloc] init];
[datFormat setTimeZone:[NSTimeZone timeZoneWithName:@"Yout TimeZone"]];
[datFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
NSString *string = @"2012-05-03 06:03:00 +0000";
NSDate* date = [datFormat dateFromString:string];