WayWay WayWay - 4 months ago 10
iOS Question

iOS and finding Tomorrow

How can I check to see if a date is inherently TOMORROW?

I don't want to add hours or anything to a date like today, because if today is already

22:59
, adding too much would go over to the day after, and adding too little if the time is
12:00
would miss tomorrow.

How can I check two
NSDate
s and ensure that one is the equivalent of tomorrow for the other?

Answer

Using NSDateComponents you can extract day/month/year components from the date representing today, ignoring the hour/minutes/seconds components, add one day, and rebuild a date corresponding to tomorrow.

So imagine you want to add exactly one day to the current date (including keeping hours/minutes/seconds information the same as the "now" date), you could add a timeInterval of 24*60*60 seconds to "now" using dateWithTimeIntervalSinceNow, but it is better (and DST-proof etc) to do it this way using NSDateComponents:

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

But if you want to generate the date corresponding to tomorrow at midnight, you could instead just retrieve the month/day/year components of the date representing now, without hours/min/secs part, and add 1 day, then rebuild a date:

// 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.: You can read really useful advice and stuff about date concepts in the Date and Time Programming Guide, especially here about date components.