How do I add 1 day to an NSDate?

2019-01-01 01:16发布

Basically, as the title says. I'm wondering how I could add 1 day to an NSDate.

So if it were:

21st February 2011

It would become:

22nd February 2011

Or if it were:

31st December 2011

It would become:

1st January 2012.

24条回答
只若初见
2楼-- · 2019-01-01 02:04
NSDate *today=[NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents *components=[[NSDateComponents alloc] init];
components.day=1;
NSDate *targetDate =[calendar dateByAddingComponents:components toDate:today options: 0];
查看更多
大哥的爱人
3楼-- · 2019-01-01 02:04
NSDate *now = [NSDate date];
int daysToAdd = 1;
NSDate *tomorrowDate = [now dateByAddingTimeInterval:60*60*24*daysToAdd];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEEE, dd MMM yyyy"];
NSLog(@"%@", [dateFormatter stringFromDate:tomorrowDate]);
查看更多
萌妹纸的霸气范
4楼-- · 2019-01-01 02:05

You can use NSDate's method - (id)dateByAddingTimeInterval:(NSTimeInterval)seconds where seconds would be 60 * 60 * 24 = 86400

查看更多
笑指拈花
5楼-- · 2019-01-01 02:07

Use the below function and use days paramater to get the date daysAhead/daysBehind just pass parameter as positive for future date or negative for previous dates:

+ (NSDate *) getDate:(NSDate *)fromDate daysAhead:(NSUInteger)days
{
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    dateComponents.day = days;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *previousDate = [calendar dateByAddingComponents:dateComponents
                                                     toDate:fromDate
                                                    options:0];
    [dateComponents release];
    return previousDate;
}
查看更多
后来的你喜欢了谁
6楼-- · 2019-01-01 02:07

Swift 4, if all you really need is a 24 hour shift (60*60*24 seconds) and not "1 calendar day"

Future: let dayAhead = Date(timeIntervalSinceNow: TimeInterval(86400.0))

Past: let dayAgo = Date(timeIntervalSinceNow: TimeInterval(-86400.0))

查看更多
查无此人
7楼-- · 2019-01-01 02:12

Swift 4.0 (same as Swift 3.0 in this wonderful answer just making it clear for rookies like me)

let today = Date()
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: today)
查看更多
登录 后发表回答