相关疑难解决方法(0)

处理NSDateFormatter语言环境"feechur"的最佳方法是什么?

似乎NSDateFormatter有一个"功能"意外地咬你:如果你做一个简单的"固定"格式操作,如:

NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
[fmt setDateFormat:@"yyyyMMddHHmmss"];
NSString* dateStr = [fmt stringFromDate:someDate];
[fmt release];
Run Code Online (Sandbox Code Playgroud)

然后它在美国和大多数区域设置工作正常UNTIL ...将手机设置为24小时区域的人将设置中的12/24小时开关设置为12.然后上面开始将"AM"或"PM"添加到结果字符串的结尾.

(参见,例如,NSDateFormatter,我做错了什么或者这是一个错误?)

(请参阅https://developer.apple.com/library/content/qa/qa1480/_index.html)

显然苹果公司宣称这是"不好" - 破碎如设计,他们不会解决它.

规避显然是为特定区域(通常是美国)设置日期格式化程序的区域设置,但这有点乱:

NSLocale *loc = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[df setLocale: loc];
[loc release];
Run Code Online (Sandbox Code Playgroud)

在onsies-twosies中并没有太糟糕,但我正在处理大约十个不同的应用程序,而我看到的第一个应用程序有43个这种情况的实例.

因此,对于宏/重写类/任何最小化改变所有内容的努力的任何聪明的想法,而不使代码模糊?(我的第一直觉是使用在init方法中设置语言环境的版本来覆盖NSDateFormatter.需要更改两行 - alloc/init行和添加的导入.)

添加

这是我到目前为止所提出的 - 似乎适用于所有场景:

@implementation BNSDateFormatter

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

@end …
Run Code Online (Sandbox Code Playgroud)

iphone locale objective-c nsdateformatter ios

164
推荐指数
3
解决办法
4万
查看次数

DateFormatter不返回"HH:mm:ss"的日期

这是代码摘录:

func mapping(map: Map) {
    time      <- (map["time"], TransformOf<Date, String>(fromJSON: {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "HH:mm:ss"
        //dateFormatter.timeZone = TimeZone(abbreviation: "EEST")
        if let argument = $0 {
            let date = dateFormatter.date(from: argument)
            return dateFormatter.date(from: argument)
        }
        return nil
        }}
Run Code Online (Sandbox Code Playgroud)

$0是字符串"22:12:00".我把"让日期"看看它返回的是什么,它是零.我在这里查找格式代码:http://waracle.net/iphone-nsdateformatter-date-formatting-table/

代码应该实际工作.我究竟做错了什么?

编辑:添加了整个功能

EDIT2:我刚刚注意到它在iPhone 7 iOS 10.1模拟器上运行正常但在我的iPod 10.1.1(2016)上返回nil.这太奇怪了.

date ios swift swift3

16
推荐指数
1
解决办法
3399
查看次数

当系统设置为使用24小时格式时,如何获得12小时格式时间字符串

我想得到一个像"10:00 PM"的时间字符串,我使用NSDateFormatterShortStyle来实现这一点.但是,当系统设置为使用24小时格式时,我得到的是"22:00".

此外,我想获得一个本地化的时间字符串.例如,在中文中,我希望得到"下午10:00"而不是"晚上10:00".所以我必须使用[NSLocale currentLocale],并且不能使用en_US_POSIX语言环境.

请帮我获取一个本地化的12小时格式时间字符串.

我不仅需要小时部分,还需要上午/下午部分.此外,am/pm部分可能位于小时/分钟部分之前或小时/分钟部分之后,具体取决于地区.就像系统显示时间一样.当系统设置为使用12小时格式时,它很简单.但是当系统使用24小时格式时,我无法获得本地化的12小时格式时间字符串.

datetime locale ios

3
推荐指数
1
解决办法
1万
查看次数

标签 统计

ios ×3

locale ×2

date ×1

datetime ×1

iphone ×1

nsdateformatter ×1

objective-c ×1

swift ×1

swift3 ×1