0

我住在印度,格林威治标准时间 +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

4

2 回答 2

4

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

于 2013-06-05T18:17:11.360 回答
2

您可以使用以下命令执行此操作NSDateFormatter

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];

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

其他时区可以这样找到NSTimeZone

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

希望有帮助!

于 2013-06-05T18:22:08.053 回答