我在NSDateComponentsFormatter上的allowsFractionalUnits做错了什么?



基本上我想要的是获得时间间隔的值,仅以小时表示,而不是四舍五入到完整的小时(使用NSDateComponentsFormatter来获得正确的格式和本地化)。我不知道我是否误解了NSDateComponentsFormatter的使用。allowsFractionalUnits,但我无法让格式化程序给我一个十进制值。有没有人能帮我指出我的错误,或者告诉我我误解了什么?

来自Apple文档关于allowsFractionalUnits属性:

当一个值不能精确时,可以使用小数单位用可用的单位表示。例如,如果分钟不是允许,值" 1h 30m "可以格式化为" 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"

更新:我已经向苹果报告了这个问题的bug (rdar://22660145)。

根据Open Radar #32024200:

在做了一些挖掘(反汇编Foundation)之后,看起来每个调用-[_unitFormatter stringFromNumber:]在-[NSDateComponentsFormatter _stringFromDateComponents:]传递一个+[NSNumber numberWithInteger:],它会丢弃浮点数据。

你没做错什么。

看一下文档,它使用了很多有趣的语言(强调我的):

小数单位可以在一个值不能用可用的单位精确表示时使用。例如,如果分钟不允许,值" 1h 30m " 可以格式化为" 1.5h "。

虽然对我来说,似乎只有文档中的值是实际工作的值才有意义,但当然有可能存在时间值、格式化器选项和日历/区域设置的某种组合,使其工作。在功能和文档方面,绝对值得提交Radar。

在这里输入代码据我所知,您想以12小时格式显示时间,对吗?代码如下:斯威夫特->

let dateAsString = "20:30"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH:mm"
let date = dateFormatter.dateFromString(dateAsString)
dateFormatter.dateFormat = "h:mm a"
let date12 = dateFormatter.stringFromDate(date!)
txtText.text = date12 

最新更新