Specific date after number of dates

2019-08-06 13:09发布

问题:

Currently I'm working on NSDate and NSDateFormatter.

My issue is I need to find the date after 100 days of the user specified date.

Currently I'm using this hard-coded string for finding a future date.

calendar.maximumDate = [self.dateFormatter dateFromString:@"20/08/2015"];

But it is not correct way and not work with user specified date. Is there anyway to achieve this ?

Please help me.

Thanks in advance.

回答1:

Like this:

// How much day to add
int addDaysCount = 100;

// Create and initialize date component instance
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setDay:addDaysCount];

// Retrieve date with increased days count
NSDate *newDate = [[NSCalendar currentCalendar] 
                          dateByAddingComponents:dateComponents 
                                          toDate:fromdateHere options:0];


回答2:

  • (id)dateWithTimeInterval:(NSTimeInterval)seconds sinceDate:(NSDate *)date does all you need.

Here's an example:

NSDate *now = [NSDate new];
NSTimeInterval hundredDaysTimeInterval = 3600*24*100;
NSDate *nowAndAHundred = [NSDate dateWithTimeInterval:hundredDaysTimeInterval sinceDate:now];


回答3:

Use dateByAddingTimeInterval function in NSDate. Like

int daysToAdd = 100;
NSDate *maximumDate = [yourDate dateByAddingTimeInterval:60*60*24*daysToAdd];


回答4:

Try the following

use nsdate instance method "- (id)dateByAddingTimeInterval:(NSTimeInterval)seconds" and pass (100 * 86400) as argument to get the date after 100 days from the user specified date. Call this method using user specified date which is instance of nsdate.