NSDate返回GMT时间

时间:2013-06-05 18:07:32

标签: cocoa timezone nsdate

我住在印度,格林尼治标准时间+5.30。当我打印系统时,它会显示当前时间。但是当我使用这段代码时,会使用GMT时间!

代码示例:

NSDate *now = [NSDate date];
NSDate *tomorrow = [now dateByAddingTimeInterval:24 * 60 * 60];
NSDate *dayaftertomorrow = [now dateByAddingTimeInterval:48 * 60 * 60];

NSLog(@"Tomorrow, the date will be %@" , tomorrow);
NSLog(@"Day after tomorrow, the date will be %@" , dayaftertomorrow);

系统时间现在是晚上11:34。但控制台打印出来:

2013-06-05 23:35:02.577 prog1 [1601:303]明天,日期将是2013-06-06 18:05:02 +0000 2013-06-05 23:35:02.578 prog1 [1601:303]后天,日期将是2013-06-07 18:05:02 +0000

2 个答案:

答案 0 :(得分:4)

创建NSDate对象后,必须使用NSDateFormatter方法stringFromDate:生成本地化为特定时区的日期字符串。如果您只是在NSDate对象上执行直接NSLog(),它将默认将日期显示为GMT

答案 1 :(得分:2)

您可以使用NSDateFormatter

执行此操作
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];

NSLog(@"Now: %@", [dateFormatter stringFromDate:[NSDate date]]);

可以使用NSTimeZone找到其他时区,如下所示:

NSLog(@"Timezones: %@", [NSTimeZone knownTimeZoneNames]);

希望有所帮助!

相关问题