Search code examples
objective-cnsdatenstimeinterval

Difference between dateWithTimeInterval:(NSTimeinterval) sincedate:(nsdate *) and (nsdate *) dateByAddingTimeInterval:(NSTimeInterval)


what is the difference between the two statements

NSDate *today = [NSDate date];
NSDate *tomarow = [today dateByAddingTimeInterval:60*60*24];
NSDate *nextday = [NSDate dateWithTimeInterval:60*60*24 sinceDate:today];

Solution

  • The only difference between the two methods is that one is a class method and the other is an instance method.

    Following code snippet demonstrates the use of both methods:

    // Today's Date
    NSDate *today = [NSDate new];
    
    // Date With Class Method
    NSDate *tomorrow1 = [NSDate dateWithTimeInterval:60*60*24 sinceDate:today];
    NSLog(@"Date from class method: %@", tomorrow1);
    
    // Date With Instance Method
    NSDate *tomorrow2 = [today dateByAddingTimeInterval:60*60*24];
    NSLog(@"Date from instance method: %@", tomorrow2);
    

    The above code snippet will give the output like following:

    Date from class method: 2012-12-27 09:35:15 +0000

    Date from instance method: 2012-12-27 09:35:15 +0000

    for more information , see NSDate