本月的第一天和最后一天
我试图迅速地获得本月的第一天和最后一天。
到目前为止,我有以下几点:
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")
但我不知道如何得到最后的date。 有没有一种内置的方法我错过了? 显然它必须考虑到闰年等。
你简单地得到本月的第一天
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)
对于月份的最后一天的date,添加月份的长度减去一秒:
let endOfMonth = startOfMonth!.dateByAddingTimeInterval(lengthOfMonth - 1)
Swift 3
Swift 3实际上变得更简单了:
- 你可以做到没有警惕(你可以如果你想,但因为
DateComponents
是一个非可选types,所以不再需要) - 使用iOS 8的
startOfDayForDate
(现在是startOfDay
),你不需要手动设置时间到12点,除非你在跨时区做一些非常疯狂的日历计算
干得好:
extension Date { func startOfMonth() -> Date { return Calendar.current.date(from: Calendar.current.dateComponents([.year, .month, .day], from: Calendar.current.startOfDay(for: self)))! } func endOfMonth() -> Date { return Calendar.current.date(byAdding: DateComponents(month: 1, day: -1), to: self.startOfMonth())! } } print(Date().startOfMonth()) // "2016-09-01 07:00:00 +0000\n" print(Date().endOfMonth()) // "2016-09-30 07:00:00 +0000\n"
使用Swift 3和iOS 10,我发现最简单的方法是使用Calendar
的dateInterval(of:for:)
:
guard let interval = calendar.dateInterval(of: .month, for: Date()) else { return }
然后你可以使用interval.start
和interval.end
来获得你需要的date。
Swift 3
许多约会的例子:
过去6个月 , 过去3个月 , 昨天,过去7天,过去30天,上个月, 当前月份开始和结束,上个月开始和结束date
let startDate = dateFormatter.string(from: Date().getThisMonthStart()!) let endDate = dateFormatter.string(from: Date().getThisMonthEnd()!) extension Date { func getLast6Month() -> Date? { return Calendar.current.date(byAdding: .month, value: -6, to: self) } func getLast3Month() -> Date? { return Calendar.current.date(byAdding: .month, value: -3, to: self) } func getYesterday() -> Date? { return Calendar.current.date(byAdding: .day, value: -1, to: self) } func getLast7Day() -> Date? { return Calendar.current.date(byAdding: .day, value: -7, to: self) } func getLast30Day() -> Date? { return Calendar.current.date(byAdding: .day, value: -30, to: self) } func getPreviousMonth() -> Date? { return Calendar.current.date(byAdding: .month, value: -1, to: self) } // This Month Start func getThisMonthStart() -> Date? { let components = Calendar.current.dateComponents([.year, .month], from: self) return Calendar.current.date(from: components)! } func getThisMonthEnd() -> Date? { let components:NSDateComponents = Calendar.current.dateComponents([.year, .month], from: self) as NSDateComponents components.month += 1 components.day = 1 components.day -= 1 return Calendar.current.date(from: components as DateComponents)! } //Last Month Start func getLastMonthStart() -> Date? { let components:NSDateComponents = Calendar.current.dateComponents([.year, .month], from: self) as NSDateComponents components.month -= 1 return Calendar.current.date(from: components as DateComponents)! } //Last Month End func getLastMonthEnd() -> Date? { let components:NSDateComponents = Calendar.current.dateComponents([.year, .month], from: self) as NSDateComponents components.day = 1 components.day -= 1 return Calendar.current.date(from: components as DateComponents)! } }
2017年…
首先,得到你需要的月份:
let cal = Calendar.current let d = Calendar.current.date(byAdding: .month, value: 0, to: Date())! // for "last month" just use -1, for "next month" just use 1, etc
要获得每月第一天的星期几,请执行以下操作:
let c = cal.dateComponents([.year, .month], from: d) let FDOM = cal.date(from: c)! let dowFDOM = cal.component(.weekday, from: FDOM) print("the day-of-week on the 1st is ... \(dowFDOM)") // so, that's 1=Sunday, 2=Monday, etc.
要获得月份的天数:
let r = cal.range(of: .day, in: .month, for: d)! let kDays = r.count print("the number of days is ... \(kDays)")
使用Swift 3,您可以select以下两个模式之一来检索一个月的第一天和最后一天。
#1。 使用Calendar
dateComponents(_:from:)
, date(from:)
和date(byAdding:to:wrappingComponents:)
方法
有了这种模式,你首先得到一个月的第一天的date,然后添加一个月,并从中删除一天,以获得该月的最后一天的date。 下面的Playground代码显示了如何设置它:
import Foundation // Set calendar and date let calendar = Calendar.current let date = calendar.date(byAdding: DateComponents(day: -10), to: Date())! // Get first day of month let firstDayComponents = calendar.dateComponents([.year, .month], from: date) let firstDay = calendar.date(from: firstDayComponents)! // Get last day of month let lastDayComponents = DateComponents(month: 1, day: -1) let lastDay = calendar.date(byAdding: lastDayComponents, to: firstDay)! // Set date formatter let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_UK") dateFormatter.dateStyle = .long dateFormatter.timeStyle = .long // Print results print(dateFormatter.string(from: date)) // Prints: 22 March 2017 at 18:07:15 CET print(dateFormatter.string(from: firstDay)) // Prints: 1 March 2017 at 00:00:00 CET print(dateFormatter.string(from: lastDay)) // Prints: 31 March 2017 at 00:00:00 CEST
#2。 使用Calendar
range(of:in:for:)
, dateComponents(_:from:)
和date(from:)
和方法
通过这种模式,您可以在一个月内获得一系列绝对日值,然后从中检索月份的第一天和最后一天的date。 下面的Playground代码显示了如何设置它:
import Foundation // Set calendar and date let calendar = Calendar.current let date = calendar.date(byAdding: DateComponents(day: -10), to: Date())! // Get range of days in month let range = calendar.range(of: .day, in: .month, for: date)! // Range(1..<32) // Get first day of month var firstDayComponents = calendar.dateComponents([.year, .month], from: date) firstDayComponents.day = range.lowerBound let firstDay = calendar.date(from: firstDayComponents)! // Get last day of month var lastDayComponents = calendar.dateComponents([.year, .month], from: date) lastDayComponents.day = range.upperBound - 1 //lastDayComponents.day = range.count // also works let lastDay = calendar.date(from: lastDayComponents)! // Set date formatter let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_UK") dateFormatter.dateStyle = .long dateFormatter.timeStyle = .long // Print results print(dateFormatter.string(from: date)) // prints: 22 March 2017 at 18:07:15 CET print(dateFormatter.string(from: firstDay)) // prints: 1 March 2017 at 00:00:00 CET print(dateFormatter.string(from: lastDay)) // prints: 31 March 2017 at 00:00:00 CEST
在swift 3中,如果您将0设置为date分量,则可以获取该月份的最后一天。 有一个示例代码:
public func isMoreDays(date: Date, asc: Bool)->Bool{ //components var dayComponents = self.getDateComponents(date: date) //asc is true if ascendant or false if descendant dayComponents.day = asc ? 0 : 1 //plus 1 to month 'cos if you set up day to 0 you are going to the previous month dayComponents.month = asc ? dayComponents.month! + 1 : dayComponents.month //instantiate calendar and get the date let calendar : Calendar = NSCalendar.current let day = calendar.date(from: dayComponents) //date comparison if(day?.compare(date) == .orderedSame){ return false } return true }