2016-11-20 56 views
1

我試圖從guide獲取兩個日期的時差。我不知道該怎麼投入dateComponents的論點。當我在[.hour, .minute]直接傳遞,我得到一個錯誤:在Swift中獲取時差3

Playground execution failed: error: MyPlayground.playground:10:46: error: type of expression is ambiguous without more context 
let timeDifference = calendar.dateComponents([.hour, .minute], from: stopTime!, to: date!) 
              ^~~~~~~~~~~~~~~~ 

```

我試圖將其聲明爲一個常數第一,但我不能確定是什麼類型。參數的類型爲Set<Calendar.Component>,但是當我試圖說明它是Component,DateComponentCalendarComponent時,出現錯誤。

````

let timeFormatter = DateFormatter() 
timeFormatter.dateFormat = "hh:mm a " 
let time = "12:03 pm" 
let stopTime = timeFormatter.date(from: time) 

let date = Date() 
let calendar = Calendar.current 

let components:[DateComponent] = [.hour, .minute] 
let timeDifference = calendar.dateComponents(components, from: stopTime!, to: date!) 

回答

5

dateComponents(_:from:to:)方法聲明如下:

public func dateComponents(_ components: Set<Calendar.Component>, 
    from start: Date, to end: Date) -> DateComponents 

第一個參數是Set<Calendar.Components>類型,但你似乎提供了一個[DateComponents]。這就是你看到錯誤的原因。

因此,它應該做的是這樣的:

let components:[Calendar.Component] = [.hour, .minute] 
let timeDifference = calendar.dateComponents(Set<Calendar.Component>(components), 
    from: stopTime!, to: date) 

首先,我改變了陣列的類型爲[Calendar.Component]。其次,在將components傳遞給方法之前,我創建了Set<Calendar.Component>。另一件事是你寫了date!!是多餘的,因爲date已經是非可選的。無需解開!

或者,您可以完全刪除components變量!

let timeDifference = calendar.dateComponents([.hour, .minute], 
    from: stopTime!, to: date) 

現在編譯好了!

然而,這可能不會產生預期的結果,因爲timeFormatter.date(from: time)產生在2000年。我得到了這個相當骯髒的解決方案的日期,但它的工作原理呢:

let timeFormatter = DateFormatter() 
timeFormatter.dateFormat = "hh:mm a" 
let time = "08:00 pm" 
var stopTime = timeFormatter.date(from: time) 

let date = Date() 
let calendar = Calendar.current 

let year = calendar.component(.year, from: date) 
let month = calendar.component(.month, from: date) 
let day = calendar.component(.day, from: date) 
let hour = calendar.component(.hour, from: stopTime!) 
let minute = calendar.component(.minute, from: stopTime!) 

stopTime = calendar.date(bySetting: .year, value: year, of: stopTime!) 
stopTime = calendar.date(bySetting: .month, value: month, of: stopTime!) 
stopTime = calendar.date(bySetting: .day, value: day, of: stopTime!) 
stopTime = calendar.date(bySetting: .hour, value: hour, of: stopTime!) 
stopTime = calendar.date(bySetting: .minute, value: minute, of: stopTime!) 

let timeDifference = calendar.dateComponents([.hour, .minute], from: stopTime!, to: date) 
+0

您無需顯式創建'Set '。嘗試在代碼中用'[.hour,.minute]'替換'Set (components)'。 – OOPer

+0

哦,是的!我從來不知道'''''也可以表示一個'Set'。 @OOPer – Sweeper

+0

請注意,OP的問題是由'date!'中的'!'引起的。 – OOPer

0

雨燕3.0

let start = Date(); 
//Your functions.. 
let end = Date(); 
print("Time to do something: \(end.timeIntervalSince(start)) seconds");