我正在设法迅速获得每月的第一天和最后一天。
到目前为止,我有以下内容:
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")
但是我不确定如何获得最后的约会。我是否缺少内置方法?显然,它必须考虑leap年等。
您只需使用以下命令即可获得每月的第一天
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为您提供开始时间和月份长度的方法:
rangeOfUnit
var startOfMonth : NSDate? var lengthOfMonth : NSTimeInterval = 0 calendar.rangeOfUnit(.Month, startDate: &startOfMonth, interval: &lengthOfMonth, forDate: date)
对于月份的最后一天的日期,请加上月份的长度减去一秒:
let endOfMonth = startOfMonth!.dateByAddingTimeInterval(lengthOfMonth - 1)
为Swift5更新:
extension Date { var startOfDay: Date { return Calendar.current.startOfDay(for: self) } var startOfMonth: Date { let calendar = Calendar(identifier: .gregorian) let components = calendar.dateComponents([.year, .month], from: self) return calendar.date(from: components)! } var endOfDay: Date { var components = DateComponents() components.day = 1 components.second = -1 return Calendar.current.date(byAdding: components, to: startOfDay)! } var endOfMonth: Date { var components = DateComponents() components.month = 1 components.second = -1 return Calendar(identifier: .gregorian).date(byAdding: components, to: startOfMonth)! } func isMonday() -> Bool { let calendar = Calendar(identifier: .gregorian) let components = calendar.dateComponents([.weekday], from: self) return components.weekday == 2 } }