Reputation: 835
How can I fire a UILocalNotification two days before a given NSDate?
Upvotes: 0
Views: 98
Reputation: 19
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)];
}
Upvotes: 1
Reputation: 13343
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.
Upvotes: 2