gpt4 book ai didi

cocoa - 有没有更好的方法来查找明天午夜?

转载 作者:行者123 更新时间:2023-12-03 16:03:23 26 4
gpt4 key购买 nike

有更好的方法吗?

-(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,我当然想要下一秒即将到来的午夜。

自然语言函数看起来很不稳定,我不确定如果我在“day”字段中传递了 32,Cocoa 会做什么。 (如果那行得通,我可以删除 [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 Dates and Times Programming Topics for 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];

(我不确定这是否是最有效的实现,但它应该作为正确方向的指针。)

注意:理论上,您可以通过允许日期组件对象的值大于组件正常值的范围来减少这里的代码量(例如,简单地向日期组件添加 1,这可能会导致其具有值 32)。然而,尽管dateFromComponents:可能可以容忍越界值,但不能保证。强烈建议您不要依赖它。

关于cocoa - 有没有更好的方法来查找明天午夜?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/181459/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com