iosswift4

How to get currentUTC time in swift


I want to set count down timer in swift. I have an option is to get current time is Date() but this method is giving wrong date time when my device time set wrong.

Is it possible to get exact current UTC time in swift, so I will set count down timer with exact time remaining.

Thanks.


Solution

  • 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