0

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.

Hitesh Surani
  • 12,733
  • 6
  • 54
  • 65
Pankaj Sonava
  • 519
  • 4
  • 20

3 Answers3

3

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

LorenzOliveto
  • 7,796
  • 1
  • 20
  • 47
  • Thanks for reply. what will happen when device current time is set wrong, may be be previous or more latter date to current time. – Pankaj Sonava Apr 12 '19 at 07:30
1

Many times, I have faced the same issue if the user changed his current time then lot's of logic will disturb, Unfortunately, no luck because of Date() always returns your device date.

In well-known game Candy crush, We can not play it for a specific time if my points got over, But if I change device time to feature time then everything will be unlocked. This is the best example of your problem.

You can use below-given web service or your web service to achieve your requirements. Below are some free API's which provides date and time.

Geonames

Timezonedb

TrueTime

Hitesh Surani
  • 12,733
  • 6
  • 54
  • 65
-2

In addition to other answers, you can write an extension for Date class to get formatted Data in specific TimeZone to make it as utility function for future use. Like

extension Date {

   func dateInTimeZone(timeZoneIdentifier: String, dateFormat: String) -> String {
     let dtf = DateFormatter()
     dtf.timeZone = TimeZone(identifier: timeZoneIdentifier)
     dtf.dateFormat = dateFormat

     return dtf.string(from: self)
 }
}

Now you can call it like

Date().dateInTimeZone(timeZoneIdentifier: "UTC", dateFormat: "yyyy-MM-dd HH:mm:ss");
Asad Ali Choudhry
  • 4,985
  • 4
  • 31
  • 36