2
我使用內置的DateComponentsFormatter來計算當前日期和另一日期之間的年數。如果過去的日期,例如1940年得到太遠,返回的單位是錯誤的:DateComponentsFormatter不適用於過去的日期
let dateComponents = DateComponents(year: 1940, month: 1, day: 2, hour: 1, minute: 1, second: 1)
let date = Calendar.current.date(from: dateComponents)!
let dateComponentsFormatter = DateComponentsFormatter()
dateComponentsFormatter.allowedUnits = [.year]
dateComponentsFormatter.unitsStyle = .full
print(dateComponentsFormatter.string(from: abs(date.timeIntervalSinceNow)))
這將打印-58 years
這是不正確。這是Apple的錯誤嗎?難道我做錯了什麼?
'打印(dateComponentsFormatter.string(來源:日期,以:日期())?? 「」)' –
@LeoDabus感謝我還曾試圖哪個更好,但並不總是給出相同的價值...有時70年,有時69年 – Stephen
它給了我77年 –