【发布时间】: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,否则我会失去它而只使用T。T1只会造成混乱。
标签: ios nsdate nsdateformatter nslocale