基於此鏈接https://github.com/freak4pc/NSDate-ServerDate我寫了swift的代碼。嘗試和測試。它的工作原理。
override func viewDidLoad() {
super.viewDidLoad()
//call ServerTimeReturn function
serverTimeReturn { (getResDate) -> Void in
var dFormatter = NSDateFormatter()
dFormatter.dateStyle = NSDateFormatterStyle.LongStyle
dFormatter.timeStyle = NSDateFormatterStyle.LongStyle
dFormatter.timeZone = NSTimeZone(abbreviation: "GMT")
var dateGet = dFormatter.stringFromDate(getResDate)
println("Formatted Time : \(dateGet)")
}
}
func serverTimeReturn(completionHandler:(getResDate: NSDate!) -> Void){
let url = NSURL(string: "http://www.google.com")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
let httpResponse = response as? NSHTTPURLResponse
if let contentType = httpResponse!.allHeaderFields["Date"] as? String {
var dFormatter = NSDateFormatter()
dFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z"
var serverTime = dFormatter.dateFromString(contentType)
completionHandler(getResDate: serverTime)
}
}
task.resume()
}
爲什麼不只是將'NSDate'的時區設置爲您要使用的服務器相同,因此不需要網絡呼叫? http://stackoverflow.com/a/24917928/1186243 – sbarow
時區功能很好的基礎上的鏈接。你如何設定日期到服務器是我想知道的。因爲在我將手機上的日期設置更改爲過去或未來日期時,日期會在應用中更改:) –
查看此https://www.parse.com/questions/is-there- a-way-to-retrieve-the-current-server-time – sbarow