从用户选择的内容中获取第一个日期

问题描述 投票:-3回答:1

我有一个应用程序,用户选择他们工作的星期几,所以周一至周日是选项。我需要能够获得他们将要工作的第一天的日期。因此,如果当天是星期六,他们选择工作的第一天是星期一,我需要能够获得该星期一的日期吗?

任何帮助感恩。

swift nsdate
1个回答
3
投票

首先,您需要为工作日创建枚举:

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

第二个创建一个扩展,以返回所需的下一个工作日:

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)!
    }
}

现在您可以使用以下方法:

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"
© www.soinside.com 2019 - 2024. All rights reserved.