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

Posted

技术标签:

【中文标题】如何使用swift找到给定月份和年份的天数【英文标题】:How do I find the number of days in given month and year using swift 【发布时间】:2015-07-23 14:28:52 【问题描述】:

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

【问题讨论】:

【参考方案1】:

首先为给定的年份和月份创建一个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

【讨论】:

这绝对比我的干净很多。 嗨,马丁可以看看这个***.com/questions/31595260/… @ShresthaAshesh:我想我不能帮你解决这个问题,抱歉。 如果我们必须得到月份的所有日期怎么办 @MartinR 请问如果没有给出年份,我们只能从月份中获取日期吗?【参考方案2】:

为 Swift 3.1、Xcode 8+、ios 10+ 更新

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)

【讨论】:

也仅限 iOS 10.0+。【参考方案3】:

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



【讨论】:

【参考方案4】:

Swift 5.0

func getDaysInMonth(month: Int, year: Int) -> Int? 
        let calendar = Calendar.current

        var startComps = DateComponents()
        startComps.day = 1
        startComps.month = month
        startComps.year = year

        var endComps = DateComponents()
        endComps.day = 1
        endComps.month = month == 12 ? 1 : month + 1
        endComps.year = month == 12 ? year + 1 : year

        
        let startDate = calendar.date(from: startComps)!
        let endDate = calendar.date(from:endComps)!

        
        let diff = calendar.dateComponents([Calendar.Component.day], from: startDate, to: endDate)

        return diff.day
    
    if let numberOfDays = getDaysInMonth(month: 1, year: 2015) 
     print(numberOfDays)

     

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

【讨论】:

它在 swift 1.2 上工作,但在 NScalendarUnit.CalendarUnitDay 上的 swift 2.0 (Xcode 7) 中显示错误。 您应该在以后的问题中添加此类信息。 ***.com/questions/30798561/… 感谢您的快速帮助 Pops。【参考方案5】:

为了获得给定月份和年份的天数和所有日期,试试这个。

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】:

这里是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)

【讨论】:

这是这里唯一返回正确答案的答案。 calendar.range(of: .day, in: .year, for: Date())! 总是返回 31 @MikeHay:“...总是返回 31”——我不这么认为。如果您认为其他答案是错误的,那么我建议您对这些答案发表评论,并举一个具体的例子。【参考方案7】:

斯威夫特 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 
    


【讨论】:

【参考方案8】:

那一年呢?

下面是打印日期所在月份的天数:

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

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

【讨论】:

你好,也发现了这个bug,它的结果仅在iOS 10上为31,在iOS 11上可以正常工作。 在 iOS 13 中不起作用(我只在 iOS 13 上检查过)

以上是关于如何使用swift找到给定月份和年份的天数的主要内容,如果未能解决你的问题,请参考以下文章

SwiftUI 如何让 ForEach 循环根据 Picker 中选定月份的天数进行迭代

python 给定年份月份,返回当月对应天数

Javascript:计算给定年份的月份天数

如何在 Swift 中最好地将对象组织成月份和年份?

如何计算当前月/年的天数

用java编写:输入任意年份和月份,输出对应月份的天数。