NSDateComponentsFormatter上的allowFractionalUnits我在做什么? [英] What am I doing wrong with allowsFractionalUnits on NSDateComponentsFormatter?
问题描述
基本上我想要的是获取仅以小时表示的时间间隔的值,而不是将其舍入为整小时(使用 NSDateComponentsFormatter.allowsFractionalUnits ,但我无法让格式化程序为我提供一个十进制值.谁能帮助我发现我的错误,或以什么方式告诉我我对此有误解?
Basically what I want is to get the value of a time interval represented in hours only, without rounding it to full hours (using NSDateComponentsFormatter to get it properly formatted and localized). I don't know if I misunderstand the use of NSDateComponentsFormatter.allowsFractionalUnits, but I can't get the formatter to give me a decimal value. Can anyone help me spot my error or tell me in what way I misunderstand this?
从Apple文档中获取关于allowFractionalUnits属性的信息:
From Apple docs about allowsFractionalUnits property:
当值不能精确到时可以使用分数单位 使用可用单位表示.例如,如果分钟不是 如果允许,则值"1h 30m"的格式应为"1.5h".
Fractional units may be used when a value cannot be exactly represented using the available units. For example, if minutes are not allowed, the value "1h 30m" could be formatted as "1.5h".
快速示例代码:
let formatter = NSDateComponentsFormatter()
formatter.unitsStyle = .Abbreviated
formatter.allowedUnits = .Hour
formatter.allowsFractionalUnits = true
let onePointFiveHoursInSeconds = NSTimeInterval(1.5 * 60.0 * 60.0)
print(formatter.stringFromTimeInterval(onePointFiveHoursInSeconds)!)
//"1h" instead of expected "1.5h"
Objective-C代码中的相同示例:
Same example in Objective-C code:
NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
formatter.unitsStyle = NSDateComponentsFormatterUnitsStyleAbbreviated;
formatter.allowedUnits = NSCalendarUnitHour;
formatter.allowsFractionalUnits = YES;
NSTimeInterval onePointFiveHoursInSeconds = 1.5 * 60.0 * 60.0;
NSLog(@"%@", [formatter stringFromTimeInterval:onePointFiveHoursInSeconds]);
//"1h" instead of expected "1.5h"
更新: 我已经向Apple报告了有关此问题的错误( rdar://22660145 ).
Update: I have reported a bug to Apple about this problem (rdar://22660145).
推荐答案
根据打开雷达#32024200 :
进行一些挖掘(分解Foundation)后,似乎对-[NSDateComponentsFormatter _stringFromDateComponents:]中的-[_ unitFormatter stringFromNumber:]的每次调用都传递了+ [NSNumber numberWithInteger:],从而删除了浮点数据.
After doing some digging (disassembling Foundation), it looks like every call to -[_unitFormatter stringFromNumber:] in -[NSDateComponentsFormatter _stringFromDateComponents:] is passed an +[NSNumber numberWithInteger:] which drops floating point data.
您没有做错任何事情.该标志只是坏了.
You're not doing anything wrong. The flag is simply broken.
这篇关于NSDateComponentsFormatter上的allowFractionalUnits我在做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!