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
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 theDateComponents 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
DateComponentsused 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.