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 01:56

for swift 2.2:

let today = NSDate()
let tomorrow = NSCalendar.currentCalendar().dateByAddingUnit(
        .Day,
        value: 1,
        toDate: today,
        options: NSCalendarOptions.MatchStrictly)

Hope this helps someone!

查看更多
皆成旧梦
3楼-- · 2019-01-01 01:57
NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];
NSDate *startDate = [calendar dateFromComponents:components];
NSLog(@"StartDate = %@", startDate);

components.day += 1;
NSDate *endDate = [calendar dateFromComponents:components];
NSLog(@"EndDate = %@", endDate);
查看更多
春风洒进眼中
4楼-- · 2019-01-01 01:58
NSDateComponents *dayComponent = [[NSDateComponents alloc] init];
dayComponent.day = 1;

NSCalendar *theCalendar = [NSCalendar currentCalendar];
NSDate *nextDate = [theCalendar dateByAddingComponents:dayComponent toDate:[NSDate date] options:0];

NSLog(@"nextDate: %@ ...", nextDate);

This should be self-explanatory.

查看更多
余欢
5楼-- · 2019-01-01 01:58

Swift 2.0

let today = NSDate()    
let calendar = NSCalendar.currentCalendar()
let tomorrow = calendar.dateByAddingUnit(.Day, value: 1, toDate: today, options: NSCalendarOptions.MatchFirst)
查看更多
呛了眼睛熬了心
6楼-- · 2019-01-01 02:03

In Swift 2.1.1 and xcode 7.1 OSX 10.10.5 ,you can add any number of days forward and backwards using function

func addDaystoGivenDate(baseDate:NSDate,NumberOfDaysToAdd:Int)->NSDate
{
    let dateComponents = NSDateComponents()
    let CurrentCalendar = NSCalendar.currentCalendar()
    let CalendarOption = NSCalendarOptions()

    dateComponents.day = NumberOfDaysToAdd

    let newDate = CurrentCalendar.dateByAddingComponents(dateComponents, toDate: baseDate, options: CalendarOption)
    return newDate!
}

function call for incrementing current date by 9 days

var newDate = addDaystoGivenDate(NSDate(), NumberOfDaysToAdd: 9)
print(newDate)

function call for decrement current date by 80 days

newDate = addDaystoGivenDate(NSDate(), NumberOfDaysToAdd: -80)
 print(newDate)
查看更多
只若初见
7楼-- · 2019-01-01 02:04

In swift

var dayComponenet = NSDateComponents()
dayComponenet.day = 1

var theCalendar = NSCalendar.currentCalendar()
var nextDate = theCalendar.dateByAddingComponents(dayComponenet, toDate: NSDate(), options: nil)
查看更多
登录 后发表回答