2

I am new to iOS development. I am trying to build an app which can primarily do two things:

a. get user's system time (say, his phone is in London, so his time)

b. get the time in a given location (say, San Francisco)

and then, I want to calculate the difference in time between the location (e.g. London, UK is 8 hours ahead of San Francisco, CA)

Can someone please help me with suggestions for how can I get (a) and (b)?

Jaydeep Vora
  • 6,085
  • 1
  • 22
  • 40
AmitGupta
  • 43
  • 1
  • 6
  • Keep in mind that the time difference between two points can change. You can tell what the *current* time difference is, or the difference at some other point in time, but not just "the difference" because it's not an absolute due to daylight saving time and other time zone anomalies. – Matt Johnson-Pint Jul 28 '17 at 18:42
  • Also, keep in mid the *user's system time* is time on client side. The user can change the time in settings at any moment and it doesn't have to reflect the actual time in that location. – thisIsTheFoxe Jan 12 '23 at 20:25

2 Answers2

6

For both (a) and (b):

      let offset = TimeZone.current.secondsFromGMT();

        print(offset)//Your current timezone offset in seconds

        let loc = CLLocation.init(latitude: 48.8566, longitude: 2.3522);//Paris's lon/lat


        let coder = CLGeocoder();
        coder.reverseGeocodeLocation(loc) { (placemarks, error) in
            let place = placemarks?.last;

            let newOffset = place?.timeZone?.secondsFromGMT();

            print(newOffset);//Paris's timezone offset in seconds
        }
hoang Cap
  • 704
  • 6
  • 18
  • Keep in mind that this only works because `secondsFromGMT` defaults to the *current* date and time. – Matt Johnson-Pint Jul 28 '17 at 18:41
  • I don't quite get your words, can you please explain more? I would love to learn more about it. And if possible, can you give me a reference link? Thanks. – hoang Cap Jul 30 '17 at 23:53
-1

If you're looking for local time you can use:

NSTimeZone *timeZoneLocal = [NSTimeZone localTimeZone];  
NSString *strTimeZoneName = [timeZoneLocal name];

  or

NSTimeZone *timeZoneLocal = [NSTimeZone defaultTimeZone];
NSString *strTimeZoneName = [timeZoneLocal name];

You would probably just need two text fields and have the user compare the time difference.

Joe Hill
  • 333
  • 3
  • 12
  • `[NSTimeZone localTimeZone]` and `NSTimeZone.local` fail on the Simulator when simulating a location. They return the device's location, not the one that you have set the device to. Same for the system too. – Alex Zavatone Jul 01 '19 at 21:12