Если вы пытаетесь получить сегодняшнюю или вчерашнюю полночь в вашем часовом поясе, вы должны получить NSDate
, что указывает на адекватное время в GMT . В моем случае -2 часа, поскольку мой часовой пояс +0200, поэтому в полночь 2011-08-26 я получу 2011-08-25 22: 00.
Вы должны убедиться, что вы устанавливаете правильный часовой пояс для NSCalendar
, который равен [NSTimeZone systemTimeZone]
.
Моя процедура получения полуночи в моем часовом поясе:
+ (NSDate *)midnightOfDate:(NSDate *)date {
NSCalendar *cal = [NSCalendar currentCalendar];
[cal setTimeZone:[NSTimeZone systemTimeZone]];
NSDateComponents *components = [cal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:date];
[components setTimeZone:[cal timeZone]];
[components setHour:0];
[components setMinute:0];
[components setSecond:0];
return [cal dateFromComponents:components];
}
Итак, после длинного обсуждения в комментариях, вот функция полудня:
+ (NSDate *)middayOfDate:(NSDate *)date {
NSCalendar *cal = [NSCalendar currentCalendar];
[cal setTimeZone:[NSTimeZone systemTimeZone]];
NSDateComponents *components = [cal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:date];
[components setTimeZone:[cal timeZone]];
[components setHour:12];
[components setMinute:0];
[components setSecond:0];
return [cal dateFromComponents:components];
}