Objective C - 获取今天(明天)的第二天

2024-03-26

如何检查某个日期是否本质上是“明天”?

我不想在像今天这样的日期上添加时间或任何内容,因为如果今天已经22:59,添加太多会延续到后天,添加太少则时间到了12:00会错过明天。

我怎样才能检查两个NSDate并确保其中一个相当于另一个的明天?


Using NSDateComponents https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDateComponents_Class/Reference/Reference.html您可以从代表今天的日期中提取日/月/年部分,忽略小时/分钟/秒部分,添加一天,并重建与明天相对应的日期。

因此,假设您想在当前日期中添加一天(包括保持小时/分钟/秒信息与“现在”日期相同),您可以使用以下命令向“现在”添加 24*60*60 秒的 timeIntervaldateWithTimeIntervalSinceNow,但最好(和 DST 证明等)这样做使用NSDateComponents:

NSDateComponents* deltaComps = [[[NSDateComponents alloc] init] autorelease];
[deltaComps setDay:1];
NSDate* tomorrow = [[NSCalendar currentCalendar] dateByAddingComponents:deltaComps toDate:[NSDate date] options:0];

But 如果你想生成明天午夜对应的日期,您可以只检索代表现在的日期的月/日/年部分,没有小时/分钟/秒部分,并添加 1 天,然后重建日期:

// Decompose the date corresponding to "now" into Year+Month+Day components
NSUInteger units = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSDateComponents *comps = [[NSCalendar currentCalendar] components:units fromDate:[NSDate date]];
// Add one day
comps.day = comps.day + 1; // no worries: even if it is the end of the month it will wrap to the next month, see doc
// Recompose a new date, without any time information (so this will be at midnight)
NSDate *tomorrowMidnight = [[NSCalendar currentCalendar] dateFromComponents:comps];

P.S.:您可以阅读非常有用的建议和有关日期概念的内容日期和时间编程指南 https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DatesAndTimes/DatesAndTimes.html#//apple_ref/doc/uid/10000039i, 尤其这里关于日期组件 https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DatesAndTimes/Articles/dtCalendars.html#//apple_ref/doc/uid/TP40003470.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Objective C - 获取今天(明天)的第二天 的相关文章

随机推荐