0

服务器给出 UTC 格式的日期和时间。

2012-11-28T10:32:15+01:00

UTC 将被格式化为:2012-11-28 10:32:15 当前实际的本地日期和时间是2012-11-28 11:32:15

我想将 utc 格式保存在数据库中,稍后在 UI 中显示之前将其转换为用户的本地日期和时间。我写了以下代码。但时间偏移是错误的。即使时间偏移量为 + 1 小时,它也会在 UTC 时间上增加 2 小时而不是 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 了我做错了什么?

4

3 回答 3

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**

谢谢大家帮忙

于 2012-11-28T11:09:55.277 回答
0

更改此行

[dfLocal setDateFormat:@"yy-MM-dd HH:mm:ss"];

并将其替换为

 [dfLocal setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

快乐编码.!!!!!!

于 2012-11-28T11:01:15.547 回答
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);

我希望这可以帮助你...

于 2012-11-28T11:08:10.653 回答