我环顾四周,没有找到我需要的东西。
这是我需要的:
在 Swift 中,我想创建一个 Date(或 NSDate)对象来表示一周中的某一天以及该工作日的特定时间。我不关心年和月。
这是因为我有一个每周重复事件的系统(在特定工作日、特定时间开会,例如“每周一晚上 8 点”)。
这是我目前的代码(不起作用):
/* ################################################################## */
/**
: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
表示绝对时间点,对工作日、小时、日历、时区等一无所知。在内部表示
作为自“引用日期”2001 年 1 月 1 日(格林威治标准时间)以来的秒数。
如果你正在使用 EventKit
那么 EKRecurrenceRule
可能
更适合。它是一个用于描述重复事件的重复模式的类。
或者,将事件存储为 DateComponentsValue
,并且
必要时计算具体的Date
。
示例:每周一晚上 8 点开会:
let meetingEvent = DateComponents(hour: 20, weekday: 2)
下次 session 是什么时候?
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
关于swift - 在 Swift 中只用一个工作日和一个小时创建一个日期对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40727102/