在我的应用程序中,我从服务器接收日期作为字符串,例如“2016-09-28T16:51:15.000+0700”。我使用 NSDateFormatter 来获取 NSDate:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSZ";
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
还有另一个格式化程序,用于从 NSDate 获取字符串并在 UI 中显示它
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.timeStyle = NSDateFormatterShortStyle;
dateFormatter.dateStyle = NSDateFormatterShortStyle;
它工作正常,并根据时区显示日期和时间,但现在我要求应用程序应为所有时区显示相同的日期和时间,并且显示日期和时间应等于服务器响应的日期和时间。因此,例如,如果应用程序收到“2016-09-28T16:51:15.000+0700”,那么它应该始终显示为 9/28/2016, 4:51 PM。我该怎么做?是否可以在不更改日期和时间的响应格式的情况下实现它?
最佳答案
如果您真的想忽略接收到的字符串中的时区信息,例如使用正则表达式将其删除
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
关于ios - NSDateFormatter,显示所有时区的相同日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41083418/