如何查看日期是否固有地为明天?

我不想像今天这样在日期中添加小时数或任何内容,因为如果今天已经是22:59,那么增加太多会延续到第二天,如果添加时间太短,那么明天就会错过。

如何检查两个12:00,并确保一个等于明天的另一个?

最佳答案

使用 NSDateComponents ,您可以从代表今天的日期中提取日/月/年组成部分,而忽略小时/分钟/秒组成部分,添加一天,并重建对应于明天的日期。

因此,假设您想向当前日期准确添加一天(包括使小时/分钟/秒信息与“现在”日期保持一致),则可以使用dateWithTimeIntervalSinceNow向“现在”添加24 * 60 * 60秒的timeInterval ,但最好使用NSDateComponents这样做(并具有DST证明等):

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

但是如果您想在午夜生成与明天相对应的日期,则可以只检索表示现在的日期的月/日/年部分,,不包括小时/分钟/秒部分,然后添加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];

附注:您可以阅读有关Date and Time Programming Guide(尤其是here about date components)中日期概念的非常有用的建议和知识。

10-06 13:23