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.

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

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!



Related Topics



Leave a reply



Submit