从用户选择的内容中获取第一个日期 [英] Getting the first date from what a user has selected

查看:69
本文介绍了从用户选择的内容中获取第一个日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,用户可以在其中选择他们工作的星期几,因此可以选择周一至周日.我需要能够获得他们将工作的第一天的日期.因此,如果当前日期是星期六并且他们选择他们的第一天工作是星期一,我需要能够获得那个星期一的日期?

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?

感谢任何帮助.

推荐答案

首先你需要为工作日创建一个枚举:

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"

这篇关于从用户选择的内容中获取第一个日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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