【发布时间】:2012-02-10 21:43:36
【问题描述】:
我正在尝试将 nsstring 转换为 nsdate,然后再转换为 systemtimezone。我的代码对吗?任何帮助表示赞赏。
NSString *str=@"2012-01-15 06:27:42";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehaviorDefault];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *dateFromString = [dateFormatter dateFromString:str];
NSDate* sourceDate = dateFromString;
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT-07:00"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* destinationDate = [[[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate] autorelease];
bottomLabel2.text=[NSString stringWithFormat:@"- %@ -",destinationDate];
代码结果为2012-01-15 06:27:42 +0000 与源代码相同!
【问题讨论】:
-
"我的代码对吗?"不是这里要问的问题。 codereview.stackexchange.com
-
我不认为原始发帖人要求审查,但可能没有明确说明问题。无论如何,我已经在下面回答了。
标签: objective-c nsdate nstimezone