给定任何 NSDate,我将如何获得最后一个午夜和下一个午夜的日期?
问问题
381 次
1 回答
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];
我认为与 .NET 甚至 Java 相比,Apple 的设计有点过于复杂,但它是易于管理的。
于 2012-05-16T17:06:45.010 回答