Skip to content

Instantly share code, notes, and snippets.

@janeshsutharios
Created March 27, 2019 10:40
Show Gist options
  • Save janeshsutharios/fd6921e8fe6e589cf71c6f7046219555 to your computer and use it in GitHub Desktop.
Save janeshsutharios/fd6921e8fe6e589cf71c6f7046219555 to your computer and use it in GitHub Desktop.
Get time from internet
import UIKit
extension Formatter {
static let enUSPOSIX: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")//For 11.3.1 version change
return formatter
}()
}
extension Date {
var convertToMiliSecond: String{
let df = Formatter.enUSPOSIX
df.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let date = Date(timeInterval: 19800.0, since: self)//19800.0
print(date)
return df.string(from: date)
}
}
func getTimeFromServer(completionHandler:@escaping (_ getResDate: Date?) -> Void){
let url = URL(string: "https://www.apple.com")
let task = URLSession.shared.dataTask(with: url!) {(data, response, error) in
let httpResponse = response as? HTTPURLResponse
if let contentType = httpResponse!.allHeaderFields["Date"] as? String {
//print(httpResponse)
let dFormatter = DateFormatter()
dFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z"
//dFormatter.timeZone = TimeZone(identifier: "UTC")
let serverTime = dFormatter.date(from: contentType)
serverTime?.convertToMiliSecond
completionHandler(serverTime)
}
}
task.resume()
}
getTimeFromServer { (serverDate) in
//print(serverDate)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment