How do I find the number of days in given month and year using swift

后端 未结 8 603
庸人自扰
庸人自扰 2020-12-05 04:06

I want to find the total number days on given month and year. Example: I want to find total number of days on year = 2015, month = 7

相关标签:
8条回答
  • 2020-12-05 04:38

    here is the swift 4.0 version

    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)
    }
    
    0 讨论(0)
  • 2020-12-05 04:40

    Swift 3.1 and 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)
    
    0 讨论(0)
提交回复
热议问题