Cocoa NSDate返回GMT时间

Cocoa NSDate返回GMT时间,cocoa,timezone,nsdate,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(@"Tomorro

我住在印度,格林威治标准时间+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-0618:05:02+0000
2013-06-05 23:35:02.578 prog1[1601:303]后天,日期将是2013-06-0718:05:02+0000创建NSDate对象后,必须使用NSDateFormatter方法stringFromDate:生成本地化到特定时区的日期字符串。如果只对NSDate对象执行直接的NSLog(),则在创建NSDate对象后,默认情况下会将日期显示为GMT

,您必须使用NSDateFormatter方法stringFromDate:生成本地化到特定时区的日期字符串。如果您仅对NSDate对象执行一个直接的NSLog(),则默认情况下,它会将日期显示为GMT

您可以使用
NSDateFormatter
执行此操作:

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

NSLog(@"Now: %@", [dateFormatter stringFromDate:[NSDate date]]);
其他时区可以通过
NSTimeZone
找到,如下所示:

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

希望有帮助

您可以使用
NSDateFormatter

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

NSLog(@"Now: %@", [dateFormatter stringFromDate:[NSDate date]]);
其他时区可以通过
NSTimeZone
找到,如下所示:

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

希望有帮助

非常感谢!干杯!:)非常感谢!干杯!:)只是想澄清一下:NSDate对象单独表示线性时间中的一个时刻,与任何时区无关。当您打印它或以其他方式在某处显示它时,它将打印出某个时区中代表该时刻的日期和时间(例如,“在GMT中,该时刻是6月6日18:05”)。如果要在特定时区(包括用户的时区)打印或显示,请使用已设置为使用该时区的日期格式化程序。请澄清:NSDate对象单独表示线性时间中的一个时刻,与任何时区无关。当您打印它或以其他方式在某处显示它时,它将打印出某个时区中代表该时刻的日期和时间(例如,“在GMT中,该时刻是6月6日18:05”)。如果要在特定时区(包括用户的时区)打印或显示,请使用已设置为使用该时区的日期格式化程序。