2016-11-21 61 views
-3

有誰知道如何打印位置結束時的時間?下面的代碼打印出完整的位置時:CLLocation GeoFire位置時間

有在結果的時間之間的時間差,而印刷出來的位置和時間location?.timestamp可選:

geofire?.setLocation(location, forKey: uid) { (error) in 
      if (error != nil) { 
       print("An error occured: \(error)") 
      } else { 
       print(location) 

結果:可選( < + xx.xxxxxx,+ xx.xxxxxxxx> +/-5.00米(速度0.00 MPS /當然-1.00)@ 21/11/2016,16時04分32秒中歐標準時間)

和僅打印:

print(location?.timestamp) 

結果:可選(2016年11月21日15時04分32秒+0000)

如何打印唯一的 「16點04分32秒中歐標準時間」 甚至與「中歐標準時間」21/11/2016,16:04:32之前的日期?謝謝

+0

的可能的複製[斯威夫特 - IOS - 日期和時間以不同的格式(http://stackoverflow.com/questions/28489227/swift-ios-dates-and-times-in - 不同格式) – xoudini

回答

0

CLLocation中的時間戳只是一個Date變量。打印位置和時間戳時會得到不同的結果,因爲它們被翻譯爲兩個不同的時區。

A Date timestamp代表抽象時刻,沒有日曆系統或特定時區。另一方面,CLLocation的描述將該時間轉換爲您當地的時區,以便更好地進行說明。他們都是等同的;一個(時間戳)顯示15:04:32 GMT,另一個顯示16:04:32 Central European Standard Time,這是+1 GMT沒有DST。

從時間戳得到您的本地時間,你可以重新格式化Date對象這樣

let formatter = DateFormatter() 
    formatter.dateFormat = "HH:mm:ss" // use "dd/MM/yyyy, HH:mm:ss" if you want the date included not just the time 
    formatter.timeZone = NSTimeZone.local 
    let timestampFormattedStr = formatter.string(from: (location?.timestamp)!) // result: "16:04:32" 

    // get timezone name (Central European Standard Time in this case) 
    let timeZone = NSTimeZone(forSecondsFromGMT: NSTimeZone.local.secondsFromGMT()) 
    let timeZoneName = timeZone.localizedName(.standard, locale: NSLocale.current)! 
    let timestampWithTimeZone = "\(timestampFormattedStr!) \(timeZoneName)" // results: "16:04:32 Central European Standard Time" 

如果本地時間是你的執行至關重要,我建議檢查DST爲好。您可以檢查這樣

if timeZone.isDaylightSavingTimeForDate((location?.timestamp)!) { 

}