转换PST格式NSDate的字符串日期

时间:2016-04-13 14:25:13

标签: ios objective-c nsdate nsdateformatter

我想在目标C中将@"2016-04-15T15:00:00-07:00"转换为NSDate。我使用NSdateFormatter @"yyyy-MM-dd'T'HH:mm:ssZZZZZ"但未获得NSDate

我必须将字符串日期从服务器设置为PST时间NSDate

代码:

NSString *strDate = @"2016-04-15T22:00:00Z";

NSDate* ts_utc;

NSDateFormatter* df_utc = [[NSDateFormatter alloc] init];
[df_utc setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[df_utc setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];

ts_utc = [df_utc dateFromString:strDate];



NSDateFormatter* df_local = [[NSDateFormatter alloc] init];
[df_local setTimeZone:[NSTimeZone timeZoneWithName:@"PST"]];
[df_local setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];

NSString* ts_local_string = [df_local stringFromDate:ts_utc];


NSDate *date = [df_local dateFromString:ts_local_string];

请建议。

1 个答案:

答案 0 :(得分:0)

修改

我和你有同样的问题,我以这种方式解决了它

NSString *strDate = @"2016-04-15T22:00:00Z";
NSDate* ts_utc;
NSDateFormatter* df_utc = [[NSDateFormatter alloc] init];
[df_utc setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[df_utc setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];
ts_utc = [df_utc dateFromString:strDate];

NSTimeZone *destinationTimeZone = [NSTimeZone timeZoneWithName:@"PST"];
NSInteger timeZoneHourOffset = (NSInteger) ([destinationTimeZone secondsFromGMTForDate:ts_utc] / 3600.0); //geting the time offset between UTC and PST
NSDate *pstDate = [ts_utc dateByAddingTimeInterval:timeZoneHourOffset * 60 * 60]; //applying that offset into ts_utc NSDate

希望,这会帮助你!