Search code examples
iosnsdatenstimernstimezone

How to get the exact time of specific timzone


i am doing one application.In that i have to show the time for how much time user is in the application.For that,i calculated the difference between application opened time and current time for every one second and showing.But if i try to change the device time,that result also changing.But i want to show the exact result if user change the time also.So how to get the exact correct time based on that timezone.


Solution

  • You can set a default time zone to GMT for your application in initialize method.

    @interface AppDelegate ()
    
    @property (nonatomic, strong) NSDate startDate;
    @end
    
    @implementation AppDelegate
    
    + (void)initialize
    {
        [NSTimeZone setDefaultTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
    }
    
    - (void)applicationDidBecomeActive:(UIApplication *)application
    {
        self.startDate = [NSDate date];
    }
    
    - (void)applicationDidEnterBackground:(UIApplication *)application
    {
         NSLog(@"User has stayed for %4.2f seconds.", [[NSDate date] timeIntervalSinceDate:self.startDate]);
    }
    

    In addition to that, don't forget to set time zone for your NSDateFormatter instances when you convert a string representation of a date into actual NSDate instance.