【问题标题】:NSDateFormatter, show same date for all timezonesNSDateFormatter,为所有时区显示相同的日期
【发布时间】:2016-12-11 05:56:26
【问题描述】:

在我的应用程序中,我从服务器接收日期字符串,例如“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”,那么它应该始终将其显示为 2016 年 9 月 28 日下午 4:51。我该怎么做?是否可以在不更改日期和时间的响应格式的情况下实现它?

【问题讨论】:

  • 所有的字符串都在同一个时区(+0700)还是可以在不同的时区?如果不同,它们是否都采用相同的格式?
  • 他们可以在不同的时区,但他们总是有相同的格式。

标签: ios objective-c nsdate nsdateformatter


【解决方案1】:

如果你真的想忽略接收到的字符串中的时区信息,例如使用正则表达式将其删除

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

【讨论】:

    猜你喜欢
    • 2023-03-27
    • 2021-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-07
    • 2012-04-15
    • 2012-10-07
    • 1970-01-01
    相关资源
    最近更新 更多