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
Eraser Not Working in iOS Drawing
Swiftui Landmarks App Tutorial Screen Navigates Back When Toggle Favorite
Certificate Has Either Expired or Has Been Revoked
Add a Watermark on Video After Merging Video and Audio Asset into One in Swift3 iOS
iPhone Different Screen Sizes in Flash? (Getting Black Bars)
Presenting Uiviewcontroller from Skscene
What Is Most Common and Correct Practice to Get a Cgfloat from an Nsnumber
Xcode Exception Breakpoint Doesn't Print Details of the Exception Being Thrown
Set Custom Images to the Uibarbuttonitem But It Doesn't Show Any Image
What Is Build Object File Extension in iOS
Why Is This Code Not Recognising the Nsstring as Being Equal
Datefromstring Returns Nil for Some Values
How to Make an iOS Asset Bundle
How to Handle Push Notifications If the Application Is Already Running
How to Implement a Box or Gaussian Blur on iOS
Uifont - How to Get System Thin Font