开发者

Adding day to NSDate when a day doesn't equal 24 hours - iOS

I want to add a day to a NSDate object if its in the past (for an Alarm). However I ran into a problem if I just add 60*60*24 seconds. It adds 24 hours like what is usually wanted but in this case a day equals 23 hours. How do I fix this? Here is the following code:

 while ([alarmTime compare:[[NSDate alloc] init]] == NSOrderedAscending) {
        alarmTime = [alarmTime dateByAddingTimeInterval:(60*60*24)]; //if in the past add a day
        NSLog(开发者_如何学C@"alarm %@ is in the past, adding a day", alarmTime);
    }

22:19:59.506: alarm 03/12/2011 12:00:00 AM is in the past, adding a day
22:19:59.506: alarm 03/13/2011 12:00:00 AM is in the past, adding a day
22:19:59.507: alarm 03/14/2011 01:00:00 AM is in the past, adding a day
22:19:59.507: alarm 03/15/2011 01:00:00 AM is in the past, adding a day


This isn't a bug, it is how NSDate's description method formats the date for your logging. Remember, NSDate just stores a time interval since a reference date, so adding a days worth of seconds will always increase it by a day. In your time zone, daylight savings time begins on 13 march, so 24 hours after midnight on the day before is 1 am.

Regarding your comment of how to fix this, what do you want to fix? The code in your question will add 24 hours to alarmTime until alarmTime is in the future. If your requirement is actually that the user enters, say, 5am, and you want alarmTime to be the next 5am, then this isn't really the way to go about it, you'd be better off synthesising a new date using NSDateComponents.


Here is the code I am now using that corrects this issue:


-(void) correctDate {        
    // Create an interval of one day
    NSDateComponents *dayComponent = [[NSDateComponents alloc] init];
    dayComponent.day = 1;

    NSCalendar *theCalendar = [NSCalendar currentCalendar];

    // if its in the past, add  day
    while ([alarmTime compare:[NSDate date]] == NSOrderedAscending) {
        alarmTime = [theCalendar dateByAddingComponents:dayComponent toDate:alarmTime options:0];  //add a day

        NSLog(@"alarm %@ is in the past, adding a day", alarmTime);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜