4

目前我可以使用以下代码获取 iPhone 的当前日期

NSDate* date = [NSDate date];
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd"];
NSString* currentDateStr = [formatter stringFromDate:date];
NSLog(@"User's current Date:%@",currentDateStr);

但我想从当前日期获得下一个 15 天的日期,我怎样才能得到呢?

4

5 回答 5

6

试试这个:

NSCalendar* calendar = [[[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar] autorelease];
NSDateComponents* components = [[[NSDateComponents alloc] init] autorelease];
components.day = 15;
NSDate* newDate = [calendar dateByAddingComponents: components toDate: self.date options: 0];
于 2013-03-28T15:11:46.537 回答
1
NSDate *todayDate = [NSDate date];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setDay:+15];
NSDate *afterfifteenDays = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:todayDate options:0];
NSLog(@"todayDate: %@", todayDate);
NSLog(@"afterfifteenDays: %@", afterfifteenDays);
于 2013-03-28T15:21:17.320 回答
-1

试试这个:

NSTimeInterval totalOffset = /*time to add - in seconds */
NSDate *today = [NSDate date];
NSDate *endWithTZ = [today dateByAddingTimeInterval:totalOffset];
于 2013-03-28T15:13:53.833 回答
-2

可能有更好的方法(我正在看这个问题,看看是否有),但这是我目前使用的:

+ (NSDate *)offsetFromDate:(NSDate *)fromDate withDays:(int)days 
{
    NSTimeInterval timeInterval = (days * 86400);
    NSDate *date = [[NSDate alloc] initWithTimeInterval:timeInterval sinceDate:fromDate];    
    return date;
}

如果你用谷歌搜索一天的秒数,你会得到 86400 的值。

于 2013-03-28T15:12:48.247 回答
-2
  NSLog(@"%@", [date dateByAddingTimeInterval:15*24*60*60]);
于 2013-03-28T15:14:51.680 回答