1
NSDate *today = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setLocale:[NSLocale currentLocale]];
[calendar setTimeZone:[NSTimeZone timeZoneWithName:@"US/Central"]];

NSDateComponents *nowComponents = [calendar components:NSYearCalendarUnit | NSWeekCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:today];

[nowComponents setHour:hour];
[nowComponents setMinute:0];
[nowComponents setSecond:0];

NSLog(@"%@", [calendar dateFromComponents:nowComponents]);

日志2012-01-01 06:00:00 +0000。根据时区设置,时间是正确的,但今天是 7 月 20 日……我做错了什么?

4

1 回答 1

1

您需要提取年、月和日组件,并构造一个新的NSDate,如下所示:

NSDate *today = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setLocale:[NSLocale currentLocale]];
[calendar setTimeZone:[NSTimeZone timeZoneWithName:@"US/Central"]];

NSDateComponents *nowComponents = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:today];
today = [calendar dateFromComponents:nowComponents];

您不需要获取时间组件然后将它们设置回零:您可以通过要求首先提取它们来将它们保持在默认值。

于 2012-07-20T15:02:53.573 回答