当DateComponentsFormatter
返回意外的单位数时,我遇到了问题。有人遇到同样的问题吗?
import Foundation
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full;
formatter.maximumUnitCount = 1;
let date = Date(timeIntervalSinceNow: -14.7 * 24 * 60 * 60)
let dateString = formatter.string(from: date, to: Date()) // 2 weeks 1 day
我希望收到“2周”,但是“2周1天”。
答案 0 :(得分:3)
我通过检查逗号分隔符并使用它来子串化DateFormatters输出,Swift 3中的PlayGround示例来解决了这个问题
// Test date
var df = DateFormatter()
df.dateFormat = "dd.MM.yyyy HH:mm:ss"
df.timeZone = TimeZone(secondsFromGMT: 0)
let fromDate = df.date(from: "01.01.2000 00:00:00")
var timeDifference = Date().timeIntervalSince(fromDate!)
// Setup formatter
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
formatter.includesApproximationPhrase = false
formatter.zeroFormattingBehavior = .dropAll
formatter.maximumUnitCount = 1
formatter.allowsFractionalUnits = false
// Use the configured formatter to generate the string.
var outputString = formatter.string(from: timeDifference) ?? ""
// Remove 2nd unit if exists
let commaIndex = outputString.characters.index(of: ",") ?? outputString.endIndex
outputString = outputString.substring(to: commaIndex)
// Result
print(outputString)
答案 1 :(得分:1)
你传递的是-14.7,它被舍入为-15。所以你得到2周1天。因此,正确地对数字进行舍入以获得预期结果。
答案 2 :(得分:0)
我会提出更可靠的解决方案(虽然仍不确定它适用于所有情况)
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
formatter.maximumUnitCount = 1
let date = Date(timeIntervalSinceNow: -14.7 * 24 * 60 * 60)
let dateString = formatter.string(from: date, to: Date()) ?? ""
if let nsRange = try? NSRegularExpression(pattern: "\\A\\d* \\w*").rangeOfFirstMatch(in: dateString, options: [], range: NSRange(location: 0, length: dateString.count)), let range = Range(nsRange, in: dateString) {
let fixedString = String(dateString[range])
}
答案 3 :(得分:0)
对于那些仍在寻找答案的人来说,这就是我发现的:
目前,只有一种相对漂亮的方法可以解决这个问题,而且使用pod https://github.com/MatthewYork/DateTools。
至少在Apple解决https://openradar.appspot.com/26354907之前。
答案 4 :(得分:0)
在解决这个问题一段时间后,我设计了一个简单的解决方法,该解决方法可能(或可能不)对某些遇到此问题的人起作用。该方法的作用是,它增加了所提到的雷达故障报告中描述的导致故障出现的时间:
/// Workaround for a known bug in `DateComponentsFormatter` that causes `maximumUnitCount` variable value to be ignored sometimes https://openradar.appspot.com/26354907
///
/// - Parameters:
/// - fromDate: First (earlier) date.
/// - toDate: Second (later) date.
/// - dateFormatter: Instance of `DateComponentsFormatter` with properly set `maximumUnitCount` property.
/// - Returns: Corrected timestamp with only one unit. Eg. `1d 1h` will be corrected to `1d`.
private static func correctedTimestamp(from fromDate: Date, to toDate: Date, dateFormatter: DateComponentsFormatter) -> String? {
guard
let days = Calendar.current.dateComponents([.day], from: fromDate, to: toDate).day,
let hours = Calendar.current.dateComponents([.hour], from: fromDate, to: toDate).hour,
let minutes = Calendar.current.dateComponents([.minute], from: fromDate, to: toDate).minute,
days > 0,
days * 24 - hours == 0,
days * 24 * 60 - minutes < 0,
let timestamp = dateFormatter.string(from: fromDate, to: toDate.addingTimeInterval(Double(days * 24 * 60 - minutes) * 60))
else { return nil }
return timestamp
}