Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 我在DateComponents格式中发现错误了吗?_Ios_Swift_Nsdatecomponentsformatter - Fatal编程技术网

Ios 我在DateComponents格式中发现错误了吗?

Ios 我在DateComponents格式中发现错误了吗?,ios,swift,nsdatecomponentsformatter,Ios,Swift,Nsdatecomponentsformatter,在回答如何在比较两个日期的基础上创建“xxx ago”字符串时,我给出了该问题的完整解决方案 它涉及使用日期组件格式,将最大单位计数设置为1,将单位样式设置为.full。下面是创建日期组件格式的代码: var timeFormatter:DateComponentsFormatter = { let temp = DateComponentsFormatter() temp.allowedUnits = [.year, .month, .weekOfMonth, .day, .

在回答如何在比较两个日期的基础上创建“xxx ago”字符串时,我给出了该问题的完整解决方案

它涉及使用
日期组件格式
,将
最大单位计数
设置为1,将
单位样式
设置为
.full
。下面是创建
日期组件格式的代码:

 var timeFormatter:DateComponentsFormatter = {
    let temp = DateComponentsFormatter()
    temp.allowedUnits = [.year, .month, .weekOfMonth, .day, .hour, .minute, .second]
    temp.maximumUnitCount = 1
    temp.unitsStyle = .full
    return temp
}()
然后我编写了一个函数,它使用DateComponentFormatter输出“xxx units ago”字符串:

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


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

> P>如果你想引用很久以前的话,请考虑<代码> 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

即使没有读过这篇文章,我也可以告诉你,
datecomponentsformter
多年来一直为我产生了不一致、奇怪、有时有缺陷(即返回多个组件时限制为1)的结果。读了这篇文章后,我也经历了这种行为。@bsod你有没有就任何此类行为提交错误报告?没有,我没有。不幸的是,我是个坏孩子developer@DuncanC现在您明白我为什么说DCF有缺陷了。一个简单的解决方法是使用两个日期之间的时间间隔
timeFormatter.string(from:Date().timeIntervalSince(过去日期))
let value = Double.random(in: min ... max)
let past = now.addingTimeInterval(value)
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