You get the first day of the month just with
let components = calendar.components([.Year, .Month], fromDate: date) let startOfMonth = calendar.dateFromComponents(components)! print(dateFormatter.stringFromDate(startOfMonth)) // 2015-11-01
To get the last day of the month, add one month and subtract one day:
let comps2 = NSDateComponents() comps2.month = 1 comps2.day = -1 let endOfMonth = calendar.dateByAddingComponents(comps2, toDate: startOfMonth, options: [])! print(dateFormatter.stringFromDate(endOfMonth)) // 2015-11-30
Alternatively, use the rangeOfUnit method, which gives you the beginning and duration of the month:
var startOfMonth : NSDate? var lengthOfMonth : NSTimeInterval = 0 calendar.rangeOfUnit(.Month, startDate: &startOfMonth, interval: &lengthOfMonth, forDate: date)
For a date on the last day of the month, add the length of the month minus one second:
let endOfMonth = startOfMonth!.dateByAddingTimeInterval(lengthOfMonth - 1)
Martin R Nov 09 '15 at 9:44 2015-11-09 09:44
source share