gpt4 book ai didi

ios - NSDateComponentsFormatter 上的 allowsFractionalUnits 我做错了什么?

转载 作者:IT王子 更新时间:2023-10-29 05:04:33 25 4
gpt4 key购买 nike

基本上我想要的是获取仅以小时表示的时间间隔的值,而不将其四舍五入为整小时(使用 NSDateComponentsFormatter 使其正确格式化和本地化)。不知道是不是我理解错了NSDateComponentsFormatter.allowsFractionalUnits的用法,但我无法让格式化程序给我一个十进制值。任何人都可以帮助我发现我的错误或告诉我我以何种方式误解了这一点?

来自关于 allowsFractionalUnits 属性的 Apple 文档:

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”.

Swift 示例代码:

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 代码中的相同示例:

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)。

最佳答案

根据 Open Radar #32024200 :

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.

你没有做错任何事。旗帜简直破了。

关于ios - NSDateComponentsFormatter 上的 allowsFractionalUnits 我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32522965/

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