在我的应用程序中,在将日期插入数据库之前,我使用以下代码将字符串转换为日期。
然而,对于英国用户来说,该代码失败了,他们将地区设置为英国,时区设置为伦敦。
这适用于美国用户,因为他们的语言环境是en\u US。也就是说,此代码适用于en\u US语言环境,但不适用于en\u 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
即使日期格式正确匹配,是否仍使用区域设置?