How to get the timezone of a location in iOS app?

2019-08-01 11:52发布

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)?

2条回答
Bombasti
2楼-- · 2019-08-01 12:21

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.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-08-01 12:31

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
        }
查看更多
登录 后发表回答