Search code examples
iosobjective-cnsdatensdateformatter

NSDateFormatter, show same date for all timezones


In my application I receive dates as string from server, for example "2016-09-28T16:51:15.000+0700". I use NSDateFormatter to get NSDate:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSZ";
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];

And another formatter to get string from NSDate to display it in UI

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.timeStyle = NSDateFormatterShortStyle;
dateFormatter.dateStyle = NSDateFormatterShortStyle;

It works correctly and shows date and time depending on timezone, but now I have requirement that the application should display same date and time for all timezones and displaying date and time should be equal to date and time from server response. So for example if the application receives "2016-09-28T16:51:15.000+0700" then it should always display it as 9/28/2016, 4:51 PM. How can I do it? It is possible to achieve it without changing response format for date and time?


Solution

  • If you really really want to ignore the time zone information in the received string cut it out for example using regular expression

    NSString *dateString = @"2016-09-28T16:51:15.000+0700";
    NSString *truncatedDateString = [dateString stringByReplacingOccurrencesOfString:@"\\.\\d+(\\+|-)\\d+"
                                                                          withString:@""
                                                                             options:NSRegularExpressionSearch
                                                                               range:NSMakeRange(0, dateString.length)];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss";
    
    NSDate* date = [dateFormatter dateFromString:truncatedDateString];
    dateFormatter.dateFormat = @"M/d/yyyy h:mm a";
    NSString *finalDateString = [dateFormatter stringFromDate: date];
    NSLog(@"%@", finalDateString); // 9/28/2016 4:51 PM