目标C - 从今天(明天)开始第二天

way*_*way 20 iphone objective-c cocos2d-iphone ios

如何检查日期是否天生就是明天?

我不想在今天这样的日期添加小时或任何东西,因为如果今天已经存在22:59,那么增加太多将会持续到第二天,并且如果12:00明天错过时间会增加太少.

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

Ali*_*are 52

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

因此,想象一下你想在当前日期添加一天(包括保持小时/分钟/秒信息与"现在"日期相同),你可以在24小时60秒内添加一个timeInterval到"now"使用dateWithTimeIntervalSinceNow,但使用以下方法更好(并且防止DST等)NSDateComponents:

NSDateComponents* deltaComps = [[[NSDateComponents alloc] init] autorelease];
[deltaComps setDay:1];
NSDate* tomorrow = [[NSCalendar currentCalendar] dateByAddingComponents:deltaComps toDate:[NSDate date] options:0];
Run Code Online (Sandbox Code Playgroud)

但是如果你想在午夜生成明天对应的日期,你可以只检索现在代表的日期的月/日/年组件,而不是小时/分钟/秒部分,并添加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];
Run Code Online (Sandbox Code Playgroud)

PS:您可以在日期和时间编程指南中阅读有关日期概念的非常有用的建议和内容,特别是关于日期组件.


Kev*_*vin 6

在IOS 8有一个方便的方法上NSCalendar调用isDateInTomorrow.

Objective-C的

NSDate *date;
BOOL isTomorrow = [[NSCalendar currentCalendar] isDateInTomorrow:date];
Run Code Online (Sandbox Code Playgroud)

斯威夫特3

let date: Date
let isTomorrow = Calendar.current.isDateInTomorrow(date)
Run Code Online (Sandbox Code Playgroud)

斯威夫特2

let date: NSDate
let isTomorrow = NSCalendar.currentCalendar().isDateInTomorrow(date)
Run Code Online (Sandbox Code Playgroud)