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

时间:2015-07-23 14:28:52

标签: swift

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

8 个答案:

答案 0 :(得分:80)

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

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

let calendar = NSCalendar.currentCalendar()
let date = calendar.dateFromComponents(dateComponents)!

然后使用rangeOfUnit()方法,如中所述 Number of days in the current month using 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

更新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

答案 1 :(得分:9)

  

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)

答案 2 :(得分:5)

在扩展格式中,使用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
}

}

答案 3 :(得分:3)

Swift 2.0

func getDaysInMonth(month: Int, year: Int) -> Int
{
    let calendar = NSCalendar.currentCalendar()

    let startComps = NSDateComponents()
    startComps.day = 1
    startComps.month = month
    startComps.year = year

    let endComps = NSDateComponents()
    endComps.day = 1
    endComps.month = month == 12 ? 1 : month + 1
    endComps.year = month == 12 ? year + 1 : year

    let startDate = calendar.dateFromComponents(startComps)!
    let endDate = calendar.dateFromComponents(endComps)!

    let diff = calendar.components(NSCalendarUnit.Day, fromDate: startDate, toDate: endDate, options: NSCalendarOptions.MatchFirst)

    return diff.day
}

let days = getDaysInMonth(4, year: 2015) // April 2015 has 30 days
print(days) // Prints 30

Swift 1.2

func getDaysInMonth(month: Int, year: Int) -> Int
{
    let calendar = NSCalendar.currentCalendar()

    let startComps = NSDateComponents()
    startComps.day = 1
    startComps.month = month
    startComps.year = year

    let endComps = NSDateComponents()
    endComps.day = 1
    endComps.month = month == 12 ? 1 : month + 1
    endComps.year = month == 12 ? year + 1 : year

    let startDate = calendar.dateFromComponents(startComps)!
    let endDate = calendar.dateFromComponents(endComps)!

    let diff = calendar.components(NSCalendarUnit.CalendarUnitDay, fromDate: startDate, toDate: endDate, options: NSCalendarOptions.allZeros)

    return diff.day
}

let days = getDaysInMonth(4, 2015) // There were 30 days in April 2015
println(days) // Prints 30

答案 4 :(得分:1)

某一年怎么样?

以下是打印日期月份的天数:

let range = userCalendar.range(of: .day, in: .year, for: Date())!
print("Days In Year: \(range.count)") // prints 31

...而不是预期日期的天数:/

答案 5 :(得分:1)

为了获得给定月份和年份的天数和所有日期,请尝试此操作。

func getAllDates(month: Int, year: Int) -> [Date] {
    let dateComponents = DateComponents(year: year, month: month)
    let calendar = Calendar.current
    let date = calendar.date(from: dateComponents)!

    let range = calendar.range(of: .day, in: .month, for: date)!
    let numDays = range.count
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy MM dd"
    formatter.timeZone = TimeZone(abbreviation: "GMT+0:00")
    var arrDates = [Date]()
    for day in 1...numDays {
        let dateString = "\(year) \(month) \(day)"
        if let date = formatter.date(from: dateString) {
            arrDates.append(date)
        }
    }

    return arrDates
}

用法:

let arrDatesInGivenMonthYear = getAllDates(month: 1, year: 2018)
debugPrint(arrDatesInGivenMonthYear)
//Output: [2018-01-01 00:00:00 +0000, 2018-01-02 00:00:00 +0000, ... , 2018-01-31 00:00:00 +0000]

let numberOfDays = arrDatesInGivenMonthYear.count
debugPrint(numberOfDays)
//Output: 31

答案 6 :(得分:0)

这是Swift 4.0版本

func getTotalDate(){
    // choose the month and year you want to look
    var dateComponents = DateComponents()
    dateComponents.year = 2018
    dateComponents.month = 10

    let calendar = Calendar.current
    let datez = calendar.date(from: dateComponents)
    // change .month into .year to see the days available in the year
    let interval = calendar.dateInterval(of: .month, for: datez!)!

    let days = calendar.dateComponents([.day], from: interval.start, to: interval.end).day!
    print(days)
}

答案 7 :(得分:-1)

雨燕5

另一种解决方法:

extension Date {

    func daysInMonth(_ monthNumber: Int? = nil, _ year: Int? = nil) -> Int {
        var dateComponents = DateComponents()
        dateComponents.year = year ?? Calendar.current.component(.year,  from: self)
        dateComponents.month = monthNumber ?? Calendar.current.component(.month,  from: self)
        if
            let d = Calendar.current.date(from: dateComponents),
            let interval = Calendar.current.dateInterval(of: .month, for: d),
            let days = Calendar.current.dateComponents([.day], from: interval.start, to: interval.end).day
        { return days } else { return -1 }
    }

}