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.
let modifiedDate = Calendar. current. date(byAdding: . day, value: 1, to: today)!
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.
var lastMonthDate = Calendar. current. date(byAdding: . month, value: -1, to: date) calendar.
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 .
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With