如何使用swift查找给定月份和年份的天数

Shr*_*esh 48 swift

我想查找给定月份和年份的总天数.示例:我想查找年份= 2015年,月份= 7的总天数

Mar*_*n R 92

首先NSDate为给定的年份和月份创建一个:

let dateComponents = NSDateComponents()
dateComponents.year = 2015
dateComponents.month = 7

let calendar = NSCalendar.currentCalendar()
let date = calendar.dateFromComponents(dateComponents)!
Run Code Online (Sandbox Code Playgroud)

然后使用该rangeOfUnit()方法,如 使用iPhone SDK在当月的天数中所述?:

// Swift 2:
let range = calendar.rangeOfUnit(.Day, inUnit: .Month, forDate: date)
// Swift 1.2:
let range = calendar.rangeOfUnit(.CalendarUnitDay, inUnit: .CalendarUnitMonth, forDate: date)

let numDays = range.length
print(numDays) // 31
Run Code Online (Sandbox Code Playgroud)

更新Swift 3(Xcode 8):

let dateComponents = DateComponents(year: 2015, month: 7)
let calendar = Calendar.current
let date = calendar.date(from: dateComponents)!

let range = calendar.range(of: .day, in: .month, for: date)!
let numDays = range.count
print(numDays) // 31
Run Code Online (Sandbox Code Playgroud)


Abd*_*rim 10

Swift 3.1和Xcode 8+

let calendar = Calendar.current
let date = Date()

// Calculate start and end of the current year (or month with `.month`):
let interval = calendar.dateInterval(of: .year, for: date)! //change year it will no of days in a year , change it to month it will give no of days in a current month

// Compute difference in days:
let days = calendar.dateComponents([.day], from: interval.start, to: interval.end).day!
print(days)
Run Code Online (Sandbox Code Playgroud)


spo*_*b92 7

在扩展格式中,使用self能够更加动态地返回天数(Swift 3).

extension Date {

func getDaysInMonth() -> Int{
    let calendar = Calendar.current

    let dateComponents = DateComponents(year: calendar.component(.year, from: self), month: calendar.component(.month, from: self))
    let date = calendar.date(from: dateComponents)!

    let range = calendar.range(of: .day, in: .month, for: date)!
    let numDays = range.count

    return numDays
}

}
Run Code Online (Sandbox Code Playgroud)