Dre*_*Dre 12 performance cocoa date
有一个更好的方法吗?
-(NSDate *)getMidnightTommorow {
NSCalendarDate *now = [NSCalendarDate date];
NSCalendarDate *tomorrow = [now dateByAddingYears:0 months:0 days:1 hours:0 minutes:0 seconds:0];
return [NSCalendarDate dateWithYear:[tomorrow yearOfCommonEra]
month:[tomorrow monthOfYear]
day:[tomorrow dayOfMonth]
hour:0
minute:0
second:0
timeZone:[tomorrow timeZone]];
}
Run Code Online (Sandbox Code Playgroud)
请注意,我总是想要下一个午夜,即使它恰好在午夜时我打电话,但如果恰好是23:59:59,我当然希望午夜即将到来.
自然语言功能似乎很脆弱,如果我在"白天"字段中传递32,我不确定Cocoa会做什么.(如果那个工作我可以放弃[now dateByAddingYears:...]调用)
mma*_*alc 25
从文档:
强烈建议不要使用NSCalendarDate.它尚未弃用,但可能是在Mac OS X v10.5之后的下一个主要操作系统版本中.对于日历计算,您应该使用NSCalendar,NSDate和NSDateComponents的合适组合,如日期中的Calendars 和Cocoa的时间编程主题中所述.
遵循该建议:
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.day = 1;
NSDate *tomorrow = [gregorian dateByAddingComponents:components toDate:today options:0];
[components release];
NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
components = [gregorian components:unitFlags fromDate:tomorrow];
components.hour = 0;
components.minute = 0;
NSDate *tomorrowMidnight = [gregorian dateFromComponents:components];
[gregorian release];
[components release];
Run Code Online (Sandbox Code Playgroud)
(我不确定这是否是最有效的实现,但它应该作为正确方向的指针.)
注意:理论上,您可以通过允许日期组件对象的值大于组件的正常值范围来减少代码量(例如,只需向日组件添加1,这可能会导致其值为32 ).但是,虽然dateFromComponents:
可以容忍越界值,但不能保证.强烈建议你不要依赖它.