Chr*_*all 1 date nsdate nscalendar swift
我环顾四周,没有找到我需要的东西。
这是我需要的:
在 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
}
}
Run Code Online (Sandbox Code Playgroud)
有很多方法可以将日期解析为这个,但我想创建一个日期对象以便稍后解析。
任何援助将不胜感激。
(NS)Date表示绝对时间点,对工作日、小时、日历、时区等一无所知。在内部,它表示为自“参考日期”2001 年 1 月 1 日(GMT)以来的秒数。
如果您正在与之合作,EventKit那么EKRecurrenceRule可能更适合。它是一个用于描述重复事件的重复模式的类。
或者,将事件存储为DateComponentsValue,并在必要时计算具体值Date。
示例:每周一晚上 8 点举行会议:
let meetingEvent = DateComponents(hour: 20, weekday: 2)
Run Code Online (Sandbox Code Playgroud)
下次会议是什么时候?
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))
}
Run Code Online (Sandbox Code Playgroud)
输出:
现在:2016 年 11 月 21 日 20:20 下次会议:2016年11月28日 20:00
| 归档时间: |
|
| 查看次数: |
1632 次 |
| 最近记录: |