如何到达任何日期包围的中期的NSDates?

时间:2012-05-16 16:55:34

标签: objective-c ios nsdate

鉴于任何NSDate,我如何获得最后一个午夜和下一个午夜的日期?

1 个答案:

答案 0 :(得分:3)

这非常复杂,但可行:

NSDate *date = ...;
NSUInteger componentFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *parts = [[NSCalendar currentCalendar] components:componentFlags fromDate:date];
NSDateComponents *midnightComponents = [[NSDateComponents alloc] init];
[midnightComponents setDay:[parts day]];
[midnightComponents setMonth:[parts month]];
[midnightComponents setYear:[parts year]];
NSCalendar *cal = [[NSCalendar currentCalendar];
NSDate *midnight = [cal dateFromComponents:midnightComponents];

NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:1];
NSDate *nextMidnight = [cal dateByAddingComponents:offsetComponents toDate: midnight options:0];

我认为Apple的设计过于复杂,比如.NET甚至Java,但它是可管理的。