2013-06-05 64 views
0

我住在印度,格林威治标准时间为+5.30小时。当我打印系统时间时,它会显示当前时间。但是当我使用这个代码时,使用了GMT时间!NSDate返回格林威治标准时间

代码例如:

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年6月5日23:35:02.577 PROG1 [1601:303]明天,日期将是2013年6月6日18时05分02秒 2013-06 -05 23:35:02.578 prog1 [1601:303]后天,日期将是2013-06-07 18:05:02 +0000

回答

4

创建NSDate对象后,必须使用NSDateFormatter方法stringFromDate:生成本地化到特定时区的日期字符串。如果你刚上的NSDate做直的NSLog()对象,它会显示的日期为GMT默认

+2

只是为了阐明:单独的NSDate对象代表线性时间中的某个时刻,与任何时区无关。当您打印或以其他方式在某处显示时,它会打印出某个时区代表那一刻的日期和时间(例如,“格林威治标准时间,即6月6日18:05”)。如果您希望将其打印或显示在特定时区(包括用户的时区)中,请使用您设置为使用该时区的日期格式化程序。 –

2

你可以用一个NSDateFormatter做到这一点:

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

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

其它时区都可以用NSTimeZone这样被发现:

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

希望有所帮助!

+0

非常感谢!干杯! :) – methi1999

相关问题