有没有更好的方法来做到这一点?
-(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]]; }
请注意,我一直想要下一个午夜,即使它是午夜,当我打电话,但如果它恰好是23:59:59,我当然想要一秒钟的午夜.
自然语言功能似乎是片面的,我不知道Cocoa会如何在“day”字段中通过32. (如果这样工作,我可以删除[now dateByAddingYears:…]调用)
解决方法
从
documentation:
Use of NSCalendarDate strongly
discouraged. It is not deprecated yet,
however it may be in the next major OS
release after Mac OS X v10.5. For
calendrical calculations,you should
use suitable combinations of
NSCalendar,NSDate,and
NSDateComponents,as described in
Calendars in 07001.
接下来的建议:
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];
(如果这是最有效的实现,我不太清楚,但它应该作为指向正确方向的指针.)
注意:理论上,您可以通过允许具有大于组件正常值范围的值的日期组件对象来减少代码量(例如,简单地将1添加到日组件中,这可能导致其值为32 ).但是,尽管dateFromComponents:可以容忍超出范围的值,但不能保证.强烈建议您不要依赖它.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。