我试图快速获得本月的第一天和最后一天.
到目前为止,我有以下几点:
let dateFormatter = NSDateFormatter() let date = NSDate() dateFormatter.dateFormat = "yyyy-MM-dd" let calendar = NSCalendar.currentCalendar() let components = calendar.components([.Year,.Month,.Day,.Hour,.Minute,.Second],fromDate: date) let month = components.month let year = components.year let startOfMonth = ("\(year)-\(month)-01")
解决方法
你只需要一个月的第一天
let components = calendar.components([.Year,.Month],fromDate: date) let startOfMonth = calendar.dateFromComponents(components)! print(dateFormatter.stringFromDate(startOfMonth)) // 2015-11-01
let comps2 = NSDateComponents() comps2.month = 1 comps2.day = -1 let endOfMonth = calendar.dateByAddingComponents(comps2,toDate: startOfMonth,options: [])! print(dateFormatter.stringFromDate(endOfMonth)) // 2015-11-30
或者,使用为您提供的rangeOfUnit方法
月的开始和长度:
var startOfMonth : NSDate? var lengthOfMonth : NSTimeInterval = 0 calendar.rangeOfUnit(.Month,startDate: &startOfMonth,interval: &lengthOfMonth,forDate: date)
对于月份的最后一天的日期,将月份的长度减去一秒钟:
let endOfMonth = startOfMonth!.dateByAddingTimeInterval(lengthOfMonth - 1)