How to add one month to an NSDate?
How To Add Month To NSDate Object?
NSDate *someDate = [NSDate Date] + 30Days.....;
Solution 1:
You need to use NSDateComponents:
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setMonth:1];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *newDate = [calendar dateByAddingComponents:dateComponents toDate:originalDate options:0];
[dateComponents release]; // If ARC is not used, release the date components
Solution 2:
With iOS 8 and OS X 10.9 you can add NSCalendarUnits
using NSCalendar
:
Objective-C
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *someDate = [cal dateByAddingUnit:NSCalendarUnitMonth value:1 toDate:[NSDate date] options:0];
Swift 3
let date = Calendar.current.date(byAdding: .month, value: 1, to: Date())
Swift 2
let cal = NSCalendar.currentCalendar()
let date = cal.dateByAddingUnit(.Month, value: 1, toDate: NSDate(), options: [])
Solution 3:
For swift 3.0
extension Date {
func addMonth(n: Int) -> Date {
let cal = NSCalendar.current
return cal.date(byAdding: .month, value: n, to: self)!
}
func addDay(n: Int) -> Date {
let cal = NSCalendar.current
return cal.date(byAdding: .day, value: n, to: self)!
}
func addSec(n: Int) -> Date {
let cal = NSCalendar.current
return cal.date(byAdding: .second, value: n, to: self)!
}
}
Solution 4:
For example, to add 3
months to the current date in Swift:
let date = NSCalendar.currentCalendar().dateByAddingUnit(.MonthCalendarUnit, value: 3, toDate: NSDate(), options: nil)!
In Swift 2.0:
let date = NSCalendar.currentCalendar().dateByAddingUnit(.Month, value: 3, toDate: NSDate(), options: [])
- The new
OptionSetType
structure ofNSCalendarUnit
lets you more simply specify.Month
- Parameters that take
OptionSetType
(like theoptions:
parameter, which takesNSCalendarOptions
) can't benil
, so pass in an empty set ([]
) to represent "no options".
Solution 5:
In Swift 2.0
let startDate = NSDate()
let dateComponent = NSDateComponents()
dateComponent.month = 1
let cal = NSCalendar.currentCalendar()
let endDate = cal.dateByAddingComponents(dateComponent, toDate: startDate, options: NSCalendarOptions(rawValue: 0))