Search code examples
objective-cnsstringnstimezone

Get system time zone from NSTimeZone in "GMT 5:30" NSString format


I'm a bit new to objective C. I am trying to get system time zone in string format. I need only "GMT 5:30" in my string .

_devTimezone = (NSString*)[NSTimeZone systemTimeZone];

Solution

  • You can get date description as string and then get required substring as

    NSString *myDate = [[NSDate date] descriptionWithLocale:[NSLocale systemLocale]];
    myDate=[myDate substringWithRange:NSMakeRange(26, 9)];
    NSLog(@"%@",myDate);
    

    u would get GMT+05:30 in log.

    ****EDITED****

    if u are not sure what is index you can set date format and then access the index

    NSString *dateStr = @"Wed, 14 Oct 2015 12:53:58 +0000";
    
     // Convert string to date object
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"EE, d LLLL yyyy HH:mm:ss Z"];
    NSDate *date = [dateFormat dateFromString:dateStr];
    NSString *myDate = [date descriptionWithLocale:[NSLocale systemLocale]];
    myDate=[myDate substringWithRange:NSMakeRange(26, 9)]; 
    NSLog(@"%@",myDate);
    

    Happy Coding.. :)