iPhone - 错误的日期和疯狂

时间:2011-06-28 16:45:43

标签: iphone objective-c

我有这段代码。我得到当前的日期和时间并保留日/月/年部分,改变时间。

我注意到的第一件事是当前的日期和时间是错误的。在正确的时间前一小时。然后,我将时间改为自己的时间,这又是错误的。

这是代码:

NSDate *today = [NSDate date];
// now is june 28, 17:39 pm, printing this to console gives me 
// june 28, 16:39 pm... one hour before... this is the first problem

// then I change the time...

// get the current day, month and year
NSCalendar * gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];

NSDateComponents *dayX = [gregorian  components: NSDayCalendarUnit fromDate: data];
NSDateComponents *monthX = [gregorian  components: NSMonthCalendarUnit fromDate: data];
NSDateComponents *yearX = [gregorian  components: NSYearCalendarUnit fromDate: data];

NSInteger day = [dayX day];
NSInteger month = [monthX month];
NSInteger year = [yearX year];

// this gives me the correct day, month and year
// now, create a new date using the current day, month and year but with new hour and minute...


NSDateComponents * dateComponents = [[[NSDateComponents alloc] init] autorelease];
[dateComponents setHour:17];
[dateComponents setMinute:32];
[dateComponents setDay:day];
[dateComponents setMonth:month];
[dateComponents setYear:year];

// the new date is: 16:32????? 
// how can that be if I just set it 17:32??????????

任何线索?

感谢

1 个答案:

答案 0 :(得分:2)

时区:

在这篇文章中回答:NSDateComponents returning strange hour

[gregorian setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];