2016-11-21 58 views
1

我环顾四周,还没有找到我需要的东西。用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对象。

任何援助将不胜感激。

+2

(NS)Date表示时间的绝对点和一无所知平日,小时,日历,时区等EKRecurrenceRule](https://developer.apple。 com/reference/eventkit/ekrecurrencerule)可能更适合(或者如果你想保持简单,只需要DateComponents)。 –

+1

不相关,但DateComponents的所有组件都有默认的'nil'值,这意味着您可以省略所有未使用的组件。 – vadian

+0

是的,我认为DateComponents可能是最好的方法。如果你想将这个短语作为答案,我很乐意对你进行检查。 –

回答

1

(NS)Date代表绝对时间点,对周一至周五,小时,日历,时区等一无所知。在内部,它代表 为自“参考日期”2001年1月1日格林尼治标准时间以来的秒数。

如果你正在与EventKit然后EKRecurrenceRule可能是 更适合。这是一个用于描述重复事件重复模式的类。

或者,存储事件就像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 
+0

谢谢!我也很欣赏下一个日期示例! –

相关问题