How to get previous and next month in calendar-Swift
Try like this.
To get date of next month.
Swift 3 and Swift 4
let nextMonth = Calendar.current.date(byAdding: .month, value: 1, to: Date())
Swift 2.3 or lower
let nextMonth = NSCalendar.currentCalendar().dateByAddingUnit(.Month, value: 1, toDate: NSDate(), options: [])
To get date of previous month.
Swift 3
let previousMonth = Calendar.current.date(byAdding: .month, value: -1, to: Date())
Swift 2.3 or lower
let previousMonth = NSCalendar.currentCalendar().dateByAddingUnit(.Month, value: -1, toDate: NSDate(), options: [])
Note: To get date of next and previous month I have used todays date, you can use date from which you want next and previous month date, just change NSDate()
with your NSDate
object.
Edit: For continues traveling of next and previous months you need to store one date object currentDate and when you try to get next and previous month use that date object and update it.
For next month.
let currentDate = NSCalendar.currentCalendar().dateByAddingUnit(.Month, value: 1, toDate: currentDate, options: [])
For previous month.
let currentDate = NSCalendar.currentCalendar().dateByAddingUnit(.Month, value: -1, toDate: currentDate, options: [])
You can also use extension that will make thing easy.
Swift 3
extension Date {
func getNextMonth() -> Date? {
return Calendar.current.date(byAdding: .month, value: 1, to: self)
}
func getPreviousMonth() -> Date? {
return Calendar.current.date(byAdding: .month, value: -1, to: self)
}
}
Swift 2.3 or lower
extension NSDate {
func getNextMonth() -> NSDate?{
return NSCalendar.currentCalendar().dateByAddingUnit(.Month, value: 1, toDate: self, options: [])
}
func getPreviousMonth() -> NSDate?{
return NSCalendar.currentCalendar().dateByAddingUnit(.Month, value: -1, toDate: self, options: [])
}
}
Now just get date from currentDate.
currentDate = currentDate.getNextMonth()
currentDate = currentDate.getPreviousMonth()
var currentDate = NSDate()
func nextMonth() -> NSDate {
let nextDate = NSCalendar.currentCalendar().dateByAddingUnit(.Month, value: 1, toDate: currentDate, options: [])!
currentDate = nextDate
return nextDate
}
print(nextMonth()) // 2016-11-01 20:11:15 +0000
print(nextMonth()) // 2016-12-01 21:11:15 +0000
print(nextMonth()) // 2017-01-01 21:11:15 +0000