gpt4 book ai didi

ios - 我在 DateComponentsFormatter 中发现了错误吗?

转载 作者:行者123 更新时间:2023-12-05 06:08:16 24 4
gpt4 key购买 nike

在回答this question关于如何基于比较两个日期创建“xxx ago”字符串,我写了一个完整的问题解决方案。

它涉及使用 DateComponentsFormatter 并将 maximumUnitCount 设置为 1 并将 unitsStyle 设置为 .full。下面是创建 DateComponentsFormatter 的代码:

 var timeFormatter:DateComponentsFormatter = {
let temp = DateComponentsFormatter()
temp.allowedUnits = [.year, .month, .weekOfMonth, .day, .hour, .minute, .second]
temp.maximumUnitCount = 1
temp.unitsStyle = .full
return temp
}()

然后我写了一个函数,它使用 DateComponentsFormatter 来输出“xxx units ago”字符串:

//Use our DateComponentsFormatter to generate a string showing "n <units> ago" where units is the largest units of the difference
//Between the now date and the specified date in te past
func timefromDateToNow(_ pastDate: Date) -> String {
if let output = timeFormatter.string(from: pastDate, to: now) {
return output + " ago"
} else {
return "error"
}
}

我用这样的代码计算过去的日期:

let value = Double.random(in: min ... max)
let past = now.addingTimeInterval(value)

奇怪的是,对于 value 的某些值,我得到了字符串“0 months ago”。我能够捕获的值是 -408754.0,大约是 4 天 17 小时。

为什么调用 timeFormatter.string(from: Date(timeIntervalSinceNow: -408754.0), to: Date()) 会返回 0 个月的字符串?它应该显示“4 天”的结果!

最佳答案

如果你想引用多久以前,考虑RelativeDateTimeFormatter,例如

let formatter = RelativeDateTimeFormatter()
formatter.dateTimeStyle = .named
formatter.unitsStyle = .spellOut
formatter.formattingContext = .beginningOfSentence

let date = Date()

let longTimeAgo = date.addingTimeInterval(-10_000_000)
print(formatter.localizedString(for: longTimeAgo, relativeTo: date)) // Three months ago

let veryLongTimeAgo = date.addingTimeInterval(-100_000_000)
print(formatter.localizedString(for: veryLongTimeAgo, relativeTo: date)) // Three years ago

关于ios - 我在 DateComponentsFormatter 中发现了错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65160424/

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