Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add 1 day to an NSDate?

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. 
like image 696
Andrew Avatar asked Feb 21 '11 15:02

Andrew


People also ask

How to add 1 day to date in Swift?

let modifiedDate = Calendar. current. date(byAdding: . day, value: 1, to: today)!

How do I compare two dates in Swift?

Here we will create two different date objects using DateFormatter. Then use compare function of Date class to check whether our two different date objects are same,one date is greater than other date or one date is smaller than other date in swift.

How do I get current month and year in Swift?

var lastMonthDate = Calendar. current. date(byAdding: . month, value: -1, to: date) calendar.

How do I get the current date and time in Swiftui?

The function name is getTime. The function takes in no parameters (arguments). We instantiate a DateFormatter object, which can format a Date (which includes date and time) into a String. You must set the timeStyle of the DateFormatter to .


2 Answers

Swift 5.0 :

var dayComponent    = DateComponents() dayComponent.day    = 1 // For removing one day (yesterday): -1 let theCalendar     = Calendar.current let nextDate        = theCalendar.date(byAdding: dayComponent, to: Date()) print("nextDate : \(nextDate)") 

Objective C :

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.

like image 143
Zaky German Avatar answered Sep 25 '22 21:09

Zaky German


Since iOS 8 you can use NSCalendar.dateByAddingUnit

Example in Swift 1.x:

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

Swift 2.0:

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

Swift 3.0:

let today = Date() let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: today) 
like image 33
Rob Zombie Avatar answered Sep 23 '22 21:09

Rob Zombie