NSDateから月末を取得する関数を作ってみました。
func endOfMonth(date:NSDate) -> NSDate
{
let cal = NSCalendar.currentCalendar()
let flags : NSCalendarUnit = [.Year, .Month, .Day]
let comps : NSDateComponents = cal.components(flags , fromDate: date)
var y = comps.year
var m = comps.month
m = m + 1
if (m >= 13) {
y = y + 1
m = 1
}
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd";
let firstOfMonth : NSDate = dateFormatter.dateFromString("\(y)-\(m)-01")!
let endOfMonth : NSDate = firstOfMonth.dateByAddingTimeInterval(-60*60*24)
return endOfMonth
}
使い方
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd";
let testDate = dateFormatter.dateFromString("2014-2-1")!;
let resOut = endOfMonth(testDate) // "Feb 28, 2014, 12:00 AM"