Swift Get Server Time

How to get current date from current timezone from a time server in Swift?

If you need to make sure the date is a valid date you can use a timeserver to return the date based on the device IP, of course this will require an internet connection.

You can create a asynchronous method to return the current date regardless of the user timezone and its timezone as well:



struct Root: Codable {
let unixtime: Date
let timezone: String
}


extension URL {
static let timeIP = URL(string: "http://worldtimeapi.org/api/ip")!
static func asyncTime(completion: @escaping ((Date?, TimeZone?, Error?)-> Void)) {
URLSession.shared.dataTask(with: .timeIP) { data, response, error in
guard let data = data else {
completion(nil, nil, error)
return
}
do {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
let root = try decoder.decode(Root.self, from: data)
completion(root.unixtime, TimeZone(identifier: root.timezone), nil)
} catch {
completion(nil, nil, error)
}
}.resume()
}
}

Usage:

URL.asyncTime { date, timezone, error in
guard let date = date, let timezone = timezone else {
print("Error:", error ?? "")
return
}
print("Date:", date.description(with: .current)) // "Date: Tuesday, July 28, 2020 at 4:27:36 AM Brasilia Standard Time\n"
print("Timezone:", timezone) // "Timezone: America/Sao_Paulo (current)\n"
}

Get the local time of chosen timezone - Swift

Get the current timestamp form the firebase server and compare to the date from the last post

firebase.database.ServerValue.TIMESTAMP

Go here for reference firebase.database

for firestore

firebase.firestore.Timestamp.now()

Go here for reference firebase.firestore

How to get the current time as datetime

Update for Swift 3:

let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)

I do this:

let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: date)
let hour = components.hour
let minutes = components.minute

See the same question in objective-c How do I get hour and minutes from NSDate?

Compared to Nate’s answer, you’ll get numbers with this one, not strings… pick your choice!

How to get currentUTC time in swift

The Date class doesn't have a timezone, it's just a "point int the time line" that's the same for all the timezones. When you use a DateFormatter to convert a date to a string (or a string to a date) you can specify the timezone like this:

let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")

If you cannot trust the device date you will have to use a NTP service like this:

https://github.com/instacart/TrueTime.swift

https://github.com/jbenet/ios-ntp

Get Date and Time from Apple Server

Get Date and Time from Apple Server

I think that you should be using an Internet time server. They are using a standardized protocol called NTP. The iOS has built-in support for reading NTP server time, but this is not accessible to you as an application developer. Either you implement this yourself, or you could maybe use an open source library, like ios-ntp or HS NTP. I have not used any of them myself. It is probably a good idea to check the position of the device and figure out the timezone, to get a real bulletproof solution.

Here you could read more about the servers and stuff;
NIST Internet Time Service

Ideally, you should have a list of servers in the application. If one of them fails, you call the next NTP server in the list.

Get firebase server time cloud function

Only the functions.https.onCall in your Cloud Functions code matches with the Functions.functions().httpsCallable in your Swift code, so the other ones are meaningless here.

When you call the httpsCallable, you get a FIRHTTPSCallableResult whose data property contains whatever your Cloud Function returns, as long as it's a valid JSON type, which your new Date().getTime() seems to be



Related Topics



Leave a reply



Submit