Do you want to add a "month" or exactly 30 days? If it's 30 days, you do it like this:
// get a date
NSDate *date = [NSDate dateWithNaturalLanguageString:@"2011-01-02"];
// add 30 days to it (in seconds)
date = [date dateByAddingTimeInterval:(30 * 24 * 60 * 60)];
NSLog(@"%@", date); // 2011-02-01
Note: this will not take daylight savings time transitions or leap seconds into account. Use @TheEye's answer if you need that
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 of NSCalendarUnit lets you more simply specify .Month
Parameters that take OptionSetType (like the options: parameter, which takes NSCalendarOptions) can't be nil, so pass in an empty set ([]) to represent "no options".
let startDate = NSDate()
let dateComponent = NSDateComponents()
dateComponent.month = 1
let cal = NSCalendar.currentCalendar()
let endDate = cal.dateByAddingComponents(dateComponent, toDate: startDate, options: NSCalendarOptions(rawValue: 0))
here is function , you can reduce days , month ,day by any count
like for example here , i have reduced the current system date's year by 100 year , you can do it for day , month also
just set the counter and then store the values in array , and do whatever you want to do with that array
func currentTime(){
let date = Date()
let calendar = Calendar.current
var year = calendar.component(.year, from: date)
let month = calendar.component(.month, from: date)
let day = calendar.component(.day, from: date)
let pastyear = year - 100
var someInts = [Int]()
printLog(msg: "\(day):\(month):\(year)" )
for _ in pastyear...year {
year -= 1
print("\(year) ")
someInts.append(year)
}
print(someInts)
}
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)!
}
}