服务器提供UTC格式的日期和时间。
2012-11-28T10:32:15+01:00
utc将格式化为:2012-11-28 10:32:15
当前的实际当地日期和时间是2012-11-28 11:32:15
我想将utc格式保存在数据库中,稍后在UI中显示之前将其转换为用户的本地日期和时间。我写了以下代码。但是时间偏移是错误的。它会在utc时间增加2小时而不是1小时,尽管时间偏移是+ 1小时。
NSDateFormatter *utc = [[NSDateFormatter alloc] init];
[utc setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[utc setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *dtUTC = [utc dateFromString:@"2012-11-28 10:32:15"];
double i =[[NSTimeZone systemTimeZone] secondsFromGMTForDate:[NSDate date ]];
NSDateFormatter *dfLocal = [[NSDateFormatter alloc] init];
[dfLocal setDateFormat:@"yy-MM-dd HH:mm:ss"];
[dfLocal setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:i]];
NSDate *localDateTime= [dtUTC dateByAddingTimeInterval:i];
NSString *time =[dfLocal stringFromDate:localDateTime];
NSLog(@"original UTC %@ now local: %@", dtUTC, time);
和日志:
time offset : 1.000000
original UTC 2012-11-28 10:32:15 +0000 now local: 12-11-28 12:32:15
它应该是2012-11-28 11:32:15
但是会2012-11-28 12:32:15
我做错了什么?
答案 0 :(得分:1)
NSDateFormatter *utc = [[NSDateFormatter alloc] init];
[utc setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[utc setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *dtUTC = [utc dateFromString:@"2012-11-28 10:32:15"];
NSDateFormatter *dfLocal = [[NSDateFormatter alloc] init];
[dfLocal setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
[dfLocal setTimeZone:[NSTimeZone localTimeZone]];
NSString *time =[dfLocal stringFromDate:dtUTC];
NSLog(@"original UTC %@ now local: %@", dtUTC, time);
和日志:
time offset : 1.000000
original UTC 2012-11-28 10:32:15 +0000 now local: **2012-11-28 11:32:15**
感谢各位帮忙
答案 1 :(得分:0)
更改此行
[dfLocal setDateFormat:@"yy-MM-dd HH:mm:ss"];
并将其替换为
[dfLocal setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
快乐编码。!!!!!
答案 2 :(得分:0)
也尝试这段代码..
NSTimeZone* currentTimeZone = [NSTimeZone localTimeZone];
NSTimeZone* utcTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
NSDate *dtUTC = [utc dateFromString:@"2012-11-28 10:32:15"];
NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:sourceDate];
NSInteger gmtOffset = [utcTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval gmtInterval = gmtOffset - currentGMTOffset;
NSDateFormatter *dfLocal = [[NSDateFormatter alloc] init];
[dfLocal setDateFormat:@"yy-MM-dd HH:mm:ss"];
NSDate* localDateTime = [[[NSDate alloc] initWithTimeInterval:gmtInterval sinceDate:dtUTC] autorelease];
NSString *time =[dfLocal stringFromDate:localDateTime];
NSLog(@"original UTC %@ now local: %@", dtUTC, time);
我希望这可以帮助你...