gpt4 book ai didi

ios - NSDateFormatter - setLocale 被忽略了吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:57:39 24 4
gpt4 key购买 nike

我正在尝试解决臭名昭著的问题,即当用户将定位时间设置为 12 小时而不是默认的 24 小时时,NSDateFormatter 在不需要时返回“am/pm”日期(覆盖格式字符串)

阅读之后,似乎最好的解决方案是将 dateFormatter 语言环境设置为 en_US_POSIX(我们将其用于 API 调用,因此需要忽略任何用户偏好)

然而,它似乎被忽略了?

我有一个类别如下:

@implementation NSDateFormatter (Locale)

- (id)initWithSafeLocale {
static NSLocale* en_US_POSIX = nil;
self = [self init];
if (en_US_POSIX == nil) {
en_US_POSIX = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
}
[self setLocale:en_US_POSIX];
return self;
}

@end

然后我调用:

sharedInstance.dateFormatter = [[NSDateFormatter alloc] initWithSafeLocale];
[sharedInstance.dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];

但是,日期仍然打印为

2015-09-28 11:00:00 pm +0000

我做错了什么似乎忽略了 setLocale?

引用:What is the best way to deal with the NSDateFormatter locale "feechur"?

最佳答案

问题只是您如何使用 NSLog() 打印日期。这将调用 [NSDate description],它将使用用户的默认语言环境。

来自docs (descriptionWithLocale):

If you pass nil, NSDate formats the date in the same way as the description property.

On OS X v10.4 and earlier, this parameter was an NSDictionary object. If you pass in an NSDictionary object on OS X v10.5, NSDate uses the default user locale—the same as if you passed in [NSLocale
currentLocale]
.

相反,您应该使用日期格式化程序来打印格式化字符串。

关于ios - NSDateFormatter - setLocale 被忽略了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32737588/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com