如何获得日期的'n'工作日 [英] How to get the 'n' weekday of a Date

查看:115
本文介绍了如何获得日期的'n'工作日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将此函数转换为swift。
基本上它是什么在本周的'n'日获得。因此,例如,如果我将它与NSDate()。getWeekDay(0)一起使用,它会给我9月21日,等等。
但似乎在Swift-3中不再存在rangeOfUnit。
这是我之前在Swift-2中的实现

I need to translate this function into swift. Basically what does it get the 'n' day of the current week. So for example if i use it with NSDate().getWeekDay(0) it gives me Sun 11 Sept, and so on. But seems rangeOfUnit no longer exists in Swift-3. This was my previous implementation in Swift-2


extension NSDate {
    func getWeekDay(day: Int) -> NSDate {
        var beginningOfWeek: NSDate?
        NSCalendar.currentCalendar().rangeOfUnit(NSCalendarUnit.WeekOfYear, startDate: &beginningOfWeek, interval: nil, forDate: self)
        let comps = NSDateComponents()
        comps.day = day
        comps.minute = NSCalendar.currentCalendar().component(NSCalendarUnit.Minute, fromDate: self)
        comps.hour = NSCalendar.currentCalendar().component(NSCalendarUnit.Hour, fromDate: self)
        let nextDate = NSCalendar.currentCalendar().dateByAddingComponents(comps, toDate: beginningOfWeek!, options: .SearchBackwards)
        return nextDate!
    }
}


推荐答案

有一个替代方案可以开始
直接转换为Swift 3的那一周:

There is an alternative to get the start of the week which translates directly to Swift 3:

extension Date {
    func getWeekDay(day: Int) -> Date {
        let cal = Calendar.current
        let comps = cal.dateComponents([.weekOfYear, .yearForWeekOfYear], from: self)
        let beginningOfWeek = cal.date(from: comps)!
        let nextDate = cal.date(byAdding: .day, value: day, to: beginningOfWeek)!
        return nextDate
    }
}

这篇关于如何获得日期的'n'工作日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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