在 Swift 中仅用一个工作日和一个小时创建一个日期对象

Creating a Date Object in Swift With Just a Weekday and an Hour

我环顾四周,没有找到我需要的东西。

这是我需要的:

在 Swift 中,我想创建一个 Date(或 NSDate)对象来表示一周中的某一天以及该工作日的特定时间。我不在乎年月。

这是因为我有一个每周重复活动的系统(在特定工作日、特定时间开会,例如 "Every Monday at 8PM")。

这是我目前的代码(不起作用):

/* ################################################################## */
/**
 :returns: a Date object, with the weekday and time of the meeting.
 */
var startTimeAndDay: Date! {
    get {
        var ret: Date! = nil
        if let time = self["start_time"] {
            let timeComponents = time.components(separatedBy: ":")
            let myCalendar:Calendar = Calendar.init(identifier: Calendar.Identifier.gregorian)
            // Create our answer from the components of the result.
            let myComponents: DateComponents = DateComponents(calendar: myCalendar, timeZone: nil, era: nil, year: nil, month: nil, day: nil, hour: Int(timeComponents[0])!, minute: Int(timeComponents[1])!, second: nil, nanosecond: nil, weekday: self.weekdayIndex, weekdayOrdinal: nil, quarter: nil, weekOfMonth: nil, weekOfYear: nil, yearForWeekOfYear: nil)
            ret = myCalendar.date(from: myComponents)
        }

        return ret
    }
}

有很多方法可以将日期解析成这个,但我想创建一个 Date 对象以便稍后解析。

如有任何帮助,我们将不胜感激。

(NS)Date 表示绝对时间点,对工作日、小时、日历、时区等一无所知。在内部表示 自格林威治标准时间 "reference date" 2001 年 1 月 1 日以来的秒数。

如果您使用 EventKit,那么 EKRecurrenceRule 可能是 更适合。它是 class 用于描述重复事件的重复模式。

或者,将事件存储为 DateComponentsValue,并且 必要时计算一个具体的Date

示例:每周一晚上 8 点开会:

let meetingEvent = DateComponents(hour: 20, weekday: 2)

下次会议是什么时候?

let now = Date()
let cal = Calendar.current
if let nextMeeting = cal.nextDate(after: now, matching: meetingEvent, matchingPolicy: .strict) {
    print("now:", DateFormatter.localizedString(from: now, dateStyle: .short, timeStyle: .short))
    print("next meeting:", DateFormatter.localizedString(from: nextMeeting, dateStyle: .short, timeStyle: .short))
}

输出:

now: 21.11.16, 20:20
next meeting: 28.11.16, 20:00