如何获得给定月份的周日数? (迅速) [英] how can we get the number of sundays on an given month ? ( swift )

查看:55
本文介绍了如何获得给定月份的周日数? (迅速)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何获得给定月份的星期天数?平均为4,但我们能否获得指定月份中的确切星期日数量, 我不知道从哪里开始,所以任何有关计算周日背后逻辑的提示或与此相关的任何事情都将非常感谢并对我有帮助,

how can we get the number of sundays from an given month ? in average they are 4 but can we get the exact number of sundays in a specify month , i don't know where to start for this so any hint about the logic behind counting the sundays or any thing related to this will be much appreciated and helpful for me ,

am试图获取给定月份的总天数,并且可以使用以下代码做到这一点:

am trying to get the total number of days in a given month and somewhat am able to do that with this code :

func getNumberOfDaysInMonth (month : Int , Year : Int) -> Int{


    let dateComponents = NSDateComponents()
    dateComponents.year = Year
    dateComponents.month = month

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

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

    let numDays = range.length

    return numDays


}

但是我想从一个月中排除星期日的数量

but i want to exclude number of sundays from a month

谢谢:)

推荐答案

func getNumberOfDaysInMonth (month : Int , Year : Int) -> Int{

    let dateComponents = NSDateComponents()
    dateComponents.year = Year
    dateComponents.month = month

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

    let range = calendar.rangeOfUnit(.Day, inUnit: .Month, forDate: date)

    let numDays = range.length

    // New code starts here:

    var numberOfSundays = 0

    let dateFormatter = NSDateFormatter()

    for day in 1...numDays {

        dateComponents.day = day

        let date = calendar.dateFromComponents(dateComponents)!
        dateFormatter.dateFormat = "EEEE"
        let dayOfWeek = dateFormatter.stringFromDate(date) // Get day of week

        if dayOfWeek == "Sunday" { // Check if it's a Sunday
            numberOfSundays += 1
        }
    }

    return numDays - numberOfSundays
}

这篇关于如何获得给定月份的周日数? (迅速)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆