我该如何在Objective C中获取过去的日期?比如:
NSDate *pastDate = //some date 2 weeks ago
我该如何在Objective C中获取过去的日期?比如:
NSDate *pastDate = //some date 2 weeks ago
凭借我的经验:
NSDate *today = [NSDate date];
NSDateComponents *dc = [[[NSDateComponents alloc] init] autorelease];
[dc setDay:-14];
NSCalendar *cal = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDate *pastDate = [cal dateByAddingComponents:dc toDate:today options:0];
NSDate *today = [NSDate date];
NSLog(@"today: %@",today);
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setWeek:-2];
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
NSDate *pastDate = [currentCalendar dateByAddingComponents:dateComponents toDate:today options:0];
NSLog(@"pastDate: %@",pastDate);
NSLog输出:
today: 2011-12-07 11:52:15 +0000
pastDate: 2011-11-23 11:52:15 +0000
这个例子使用了自动引用计数(ARC)。
假设您不关心夏令时,
NSDate* pastDate = [NSDate dateWithTimeIntervalSinceNow:-2*7*24*60*60];
// Get the date which is exactly 2 weeks (14 days) ago.
NSDateComponents
和NSCalendar
,让苹果处理所有边角情况。 - zaph