NSDate对象显示错误的时间

Sur*_*ran 1 iphone objective-c ios

我正在尝试使用日期"1 oct 2013 8:00:00"创建NSDate对象.我使用了以下代码

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setYear:2013];
[components setMonth:10];
[components setDay:1];
[components setHour: 8];
[components setMinute: 00];
[components setSecond: 00];
NSDate *date = [calendar dateFromComponents:components];
Run Code Online (Sandbox Code Playgroud)

但是,当我打印日期时,它会给出错误的时间"2013-10-01 02:30:00 +0000"

das*_*ght 9

这是因为时区:您处于印度标准时间(IST)区域,比GMT落后5小时30分钟.当您设置NSDate8:00从组件,它使用您的时区,所以结果被调整,以02:30使NSDate具有正确的GMT时间.如果您想将时间设置为08:00GMT,请将您的组件设置timeZone为GMT:

[components setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
Run Code Online (Sandbox Code Playgroud)