dateWithTimeInterval:(NSTimeinterval)sincedate:(nsdate*)和(nsdate*)dateByAddingTimeInterval:(NSTimeInterval)之间的区别

ray*_*1th 1 objective-c nsdate nstimeinterval

这两个陈述有什么区别

NSDate *today = [NSDate date];
NSDate *tomarow = [today dateByAddingTimeInterval:60*60*24];
NSDate *nextday = [NSDate dateWithTimeInterval:60*60*24 sinceDate:today];
Run Code Online (Sandbox Code Playgroud)

D_D*_*D_D 5

两种方法的唯一区别是一种是类方法,另一种是实例方法.

以下代码段演示了两种方法的使用:

// 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);
Run Code Online (Sandbox Code Playgroud)

上面的代码片段将给出如下输出:

上课方法日期:2012-12-27 09:35:15 +0000

实例日期方法:2012-12-27 09:35:15 +0000

有关更多信息,请参阅NSDate