我试图快速获得本月的第一天和最后一天。
到目前为止,我有以下内容:
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")
但我不确定如何获得最后约会。我有没有内置的方法?显然它必须考虑到闰年等。
答案 0 :(得分:91)
使用Swift 3 +,这实际上可以轻松实现 :
DateComponents
现在是非可选类型,所以不再需要)。startOfDayForDate
(现在为startOfDay
),您无需手动将时间设置为12 pm,除非您在跨时区进行一些非常疯狂的日历计算。值得一提的是,其他一些答案声称您可以使用Calendar.current.date(byAdding: .month, value: 0, to: Date())!
来快速解决此问题,但如果失败,那么它实际上并不会在当天消失,或者说明时区的差异。< / p>
你走了:
extension Date {
func startOfMonth() -> Date {
return Calendar.current.date(from: Calendar.current.dateComponents([.year, .month], 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()) // "2018-02-01 08:00:00 +0000\n"
print(Date().endOfMonth()) // "2018-02-28 08:00:00 +0000\n"
答案 1 :(得分:61)
您只需使用
即可获得本月的第一天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)
答案 2 :(得分:22)
使用Swift 3&amp; iOS 10我发现这样做的最简单方法是Calendar
&#39; s dateInterval(of:for:)
:
guard let interval = calendar.dateInterval(of: .month, for: Date()) else { return }
然后,您可以使用interval.start
和interval.end
来获取所需的日期。
答案 3 :(得分:16)
Swift 3
许多日期示例:
过去6个月, 过去3个月, 昨天,过去7天,过去30天,上个月 当前月份开始&amp;结束,上个月开始&amp;结束日期
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)!
}
}
答案 4 :(得分:5)
首先,得到你需要的月份:
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)")
答案 5 :(得分:3)
Swift 4
如果您只需要序数日:
func lastDay(ofMonth m: Int, year y: Int) -> Int {
let cal = Calendar.current
var comps = DateComponents(calendar: cal, year: y, month: m)
comps.setValue(m + 1, for: .month)
comps.setValue(0, for: .day)
let date = cal.date(from: comps)!
return cal.component(.day, from: date)
}
lastDay(ofMonth: 2, year: 2018) // 28
lastDay(ofMonth: 2, year: 2020) // 29
答案 6 :(得分:3)
这是最简单的解决方案:
extension Date {
func startOfMonth() -> Date {
let interval = Calendar.current.dateInterval(of: .month, for: self)
return (interval?.start.toLocalTime())! // Without toLocalTime it give last months last date
}
func endOfMonth() -> Date {
let interval = Calendar.current.dateInterval(of: .month, for: self)
return interval!.end
}
// Convert UTC (or GMT) to local time
func toLocalTime() -> Date {
let timezone = TimeZone.current
let seconds = TimeInterval(timezone.secondsFromGMT(for: self))
return Date(timeInterval: seconds, since: self)
}}
,然后使用您的日期实例调用它们:
print(Date().startOfMonth())
print(Date().endOfMonth())
答案 7 :(得分:2)
使用Swift 3,您可以选择以下两个模式中的一个来检索一个月的第一天和最后一天。
Calendar
dateComponents(_:from:)
,date(from:)
和date(byAdding:to:wrappingComponents:)
方法使用此模式,您首先获得一个月第一天的日期,然后添加一个月并从中删除一天,以获取该月最后一天的日期。下面的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
Calendar
range(of:in:for:)
,dateComponents(_:from:)
和date(from:)
以及方法使用此模式,您可以获得一个月内的绝对日期值范围,然后从中检索该月的第一天和最后一天的日期。下面的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
答案 8 :(得分:2)
在swift 3中,如果您将0天组件放入,则可以获得该月的最后一天。有一个示例代码:
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
}
答案 9 :(得分:2)
这是我找到的最简单的方法(Swift 5+):
extension Date {
func getStart(of component: Calendar.Component, calendar: Calendar = Calendar.current) -> Date? {
return calendar.dateInterval(of: component, for: self)?.start
}
func getEnd(of component: Calendar.Component, calendar: Calendar = Calendar.current) -> Date? {
return calendar.dateInterval(of: component, for: self)?.end
}
}
答案 10 :(得分:-1)
/**
Get last day of month..
*/
private func getLastDay(year:Int, month:Int) -> Int
{
var ret:Int = -1
switch month {
case 1:
ret = 31
break
case 2:
break
case 3:
ret = 31
break
case 4:
ret = 30
break
case 5:
ret = 31
break
case 6:
ret = 30
break
case 7:
ret = 31
break
case 8:
ret = 31
break
case 9:
ret = 30
break
case 10:
ret = 31
break
case 11:
ret = 30
break
case 12:
ret = 31
break
default:
print("bad num")
}
if(month == 2)
{
ret = 28
let t4 = year % 4
let l100 = year % 100
let l400 = year % 400
if(t4 == 0 && l100 != 0)
{
ret = 29
}
if(l400 == 0)
{
ret = 29
}
}
return ret
}