Question

How can I fire a UILocalNotification two days before a given NSDate?

Was it helpful?

Solution

Assuming eventDate is the date you have:

NSDate* twoDaysEarlyDate = [[NSDate alloc] initWithTimeInterval:-(86400 * 2) sinceDate:eventDate];

That ignores any possible daylight saving change happening just before the eventDate, which is probably fine for a local notification.

An alternate method if you need to take DST changes into effect would be similar to:

NSCalendar* currentCalendar = [NSCalendar currentCalendar];
NSDateComponents* offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:-2];
NSDate* twoDaysEarlyDate = [currentCalendar dateByAddingComponents:offsetComponents toDate:eventDate options:0];

Either option works depending on your needs.

OTHER TIPS

Suppose given date is 'expirationDate' and 'twoDaysBeforeExpirationDate' is the desired date to fire UILocalNotification. Then

NSDate* expirationDate=nil;
NSDate *twoDaysBeforeExpirationDate = [expirationDate dateBySubtractingRequiredDays:2];


- (NSDate *) dateBySubtractingRequiredDays: (NSInteger) dDays
{
    return [self dateByAddingDays: (dDays * -1)];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top