2016-11-21 54 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

謝謝!我也很欣賞下一個日期示例! –

相關問題