Getting the first date from what a user has selected

非 Y 不嫁゛ 提交于 2019-12-13 09:47:22

问题


I have an app where the user selects the days of the week they work, so Monday-Sunday are the options. I need to be able to get the date of the first day that they will be working. So if the current day is Saturday and they select their first day of work is Monday, I need to be able to get the date of that Monday?

Any help grateful.


回答1:


First you need to create an enumeration for the weekdays:

extension Date {
    enum Weekday: Int {
        case sunday = 1, monday, tuesday, wednesday, thursday, friday, saturday
    }
}

Second create an extension to return the next weekday desired:

extension Date {
    var weekday: Int {
        return Calendar.current.component(.weekday, from: self)
    }
    func following(_ weekday: Weekday) -> Date {
        // **edit**
        // Check if today weekday and the passed weekday parameter are the same
        if self.weekday == weekday.rawValue {
            // return the start of day for that date
            return Calendar.current.startOfDay(for: self)
        }
        // **end of edit**
        return Calendar.current.nextDate(after: self, matching: DateComponents(weekday: weekday.rawValue), matchingPolicy: .nextTime)!
    }
}

Now you can use your method as follow:

let now = Date()

now.following(.sunday)    // "Mar 10, 2019 at 12:00 AM"
now.following(.monday)    // "Mar 11, 2019 at 12:00 AM"
now.following(.tuesday)   // "Mar 12, 2019 at 12:00 AM"
now.following(.wednesday) // "Mar 6, 2019 at 12:00 AM"
now.following(.thursday)  // "Mar 7, 2019 at 12:00 AM"
now.following(.friday)    // "Mar 8, 2019 at 12:00 AM"
now.following(.saturday)  // "Mar 9, 2019 at 12:00 AM"


来源:https://stackoverflow.com/questions/33267931/getting-the-first-date-from-what-a-user-has-selected

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!