How to convert the Date String with time zone to NSDate

試著忘記壹切 提交于 2019-12-10 14:00:00

问题


How to convert the Date String "2012-05-03 06:03:00 +0000" to NSDate. I user the code below, but it does not work:

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

回答1:


  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]);

This code prints date: 2012-05-03 09:03:00 +0300

It works. Also don't forget to set the date formatter's timeZone that you're targeting




回答2:


Can be done this way:-

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];


来源:https://stackoverflow.com/questions/10570593/how-to-convert-the-date-string-with-time-zone-to-nsdate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!