【问题标题】:when to set the NSLocale for the NSDateFormatter ?何时为 NSDateFormatter 设置 NSLocale ?
【发布时间】:2018-04-20 16:55:49
【问题描述】:

在我的应用程序中,在将日期插入数据库之前,我使用以下代码将字符串转换为日期。

但是对于英国的用户,此代码失败,他们将地区设置为英国,时区设置为伦敦。

这适用于美国用户,因为他们的语言环境是 en_US。也就是说,此代码适用于 en_US 语言环境,但不适用于 en_GB 语言环境。

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setLocale:[NSLocale currentLocale]];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T1'HH-mm-ss-SSS"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]]; //doing this as timestamp stored in server is based on UTC, hence I'm using UTC instead of systemTimeZone
 date = [dateFormatter dateFromString:theDate];

传递的字符串是:2014-6-26T121-21-6-000

如果我按如下方式设置语言环境,而不是为全球所有用户设置 currentLocale:

[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];

那么代码可以工作,但我想知道这是否会导致将来出现任何问题?

为什么我们需要设置 locale 属性来转换日期?

为什么在我的情况下 currentLocale 失败但 en_US 语言环境没有失败,即使日期格式匹配正确?

【问题讨论】:

  • 哦,我很愚蠢地注释掉 en_US_POSIX 并使用 currentLocale 却不知道为什么!感谢您的快速回复!
  • 我认为是 'T1'21 和 21 是小时表示 HH。
  • 除非你有理由使用T1,否则我会失去它而只使用TT1 只会造成混乱。

标签: ios nsdate nsdateformatter nslocale


【解决方案1】:

每当您处理 ISO 8601 或 RFC 3339 日期(即与 Web 服务交换和/或作为字符串存储在某些数据存储中的日期)时,请使用 en_US_POSIX。见Technical Note 1480

或者可以使用NSISO8601DateFormatter,而您不必处理这种愚蠢的语言环境。例如

NSString *string = @"2014-06-26T12:21:06.000Z";

NSISO8601DateFormatter *formatter = [[NSISO8601DateFormatter alloc] init];
formatter.formatOptions = NSISO8601DateFormatWithInternetDateTime | NSISO8601DateFormatWithFractionalSeconds;

NSDate *date = [formatter dateFromString:string];

此外,ISO 8601 和 RFC 3339 日期时间字符串的标准表示,您通常会使用 2014-06-26T12:21:06.000Z 这样的格式,其中:

  • 小时小于 24;
  • 数字是零填充的;
  • 小时、分钟和秒之间的分隔符是:
  • 秒和毫秒之间的分隔符是.;和
  • 您通常会在字符串末尾添加 Z 以明确指定时间字符串为 GMT/UTC/Zulu。

【讨论】:

  • 感谢您的详细解释!真的很感激!
猜你喜欢
  • 2015-12-04
  • 2012-05-17
  • 1970-01-01
  • 2014-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多