DateComponentsFormatter-相同的日期,不同的结果
为什么detteremainingtext2
给出了dateremainingtext
的不同结果?
显然,detheremainingtext2
是错误的。
这是我的代码:
import Foundation
let startDate = Calendar.current.date(from: DateComponents(year: 2022, month: 5, day: 1)) ?? .now
let endDate = Calendar.current.date(from: DateComponents(year: 2020, month: 6, day: 2)) ?? .now
let dateComponentsFormatter = DateComponentsFormatter()
dateComponentsFormatter.allowedUnits = [.year, .month, .day]
dateComponentsFormatter.unitsStyle = .full
var dateRemainingText = dateComponentsFormatter.string(from: startDate, to: endDate)! // -1 year, 10 months, 29 days
let dateComponents = Calendar.current.dateComponents([.year, .month, .day], from: startDate, to: endDate)
var dateRemainingText2 = dateComponentsFormatter.string(from: dateComponents) // -1 year, 11 months, 1 day
Why is dateRemainingText2
giving different result from dateRemainingText
?
Obviously dateRemainingText2
is wrong.
Here's my code:
import Foundation
let startDate = Calendar.current.date(from: DateComponents(year: 2022, month: 5, day: 1)) ?? .now
let endDate = Calendar.current.date(from: DateComponents(year: 2020, month: 6, day: 2)) ?? .now
let dateComponentsFormatter = DateComponentsFormatter()
dateComponentsFormatter.allowedUnits = [.year, .month, .day]
dateComponentsFormatter.unitsStyle = .full
var dateRemainingText = dateComponentsFormatter.string(from: startDate, to: endDate)! // -1 year, 10 months, 29 days
let dateComponents = Calendar.current.dateComponents([.year, .month, .day], from: startDate, to: endDate)
var dateRemainingText2 = dateComponentsFormatter.string(from: dateComponents) // -1 year, 11 months, 1 day
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
datecomponentsformatter.string(来自:to:)
and datecomponentsformatter.string(来自:)是不同的方法,因此它们可以做不同的事情。从某些实验中,我们可以看到
String(来自:)
输出一个字符串,该字符串描述了dateComponent
s中所有日期组件的 sum 传递。这只是发生的与
string的输出相同(从:to:)
对于大多数组件都是正面的情况。示例:
DateComponents
在最后情况中使用的是calendar.datecomponents(_:to:to:)
在您的代码中。另一方面,
字符串(从:到)
是格式化两个日期之间的指定方法。DateComponentsFormatter.string(from:to:)
andDateComponentsFormatter.string(from:)
are different methods and so they can do different things.From some experimentation, we can see that
string(from:)
outputs a string that describes the sum of all the date components in theDateComponent
s passed in.This just happens to be the same as the output for
string(from:to:)
for most of the cases where the components are all positive.Examples:
The
DateComponents
used in that last case is whatCalendar.dateComponents(_:from:to:)
in your code.On the other hand,
string(from:to)
is the designated method to format the period between two dates.