Crash while using Datecomponents having larger differences

落花浮王杯 提交于 2019-12-02 01:34:39

The problem seems to happen when the dateComponents of Calendar is used to get the number of seconds between two dates and the resulting number of seconds is too large to fit in a signed 32-bit integer (2^31).

An alternate solution is to use Date timeIntervalSince to get the number of seconds between two dates.

Your updated code becomes:

let dateString1 = "1979-11-28 07:57:20 +0000"
let dateString2 = "2048-11-29 10:59:00 +0000"

let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
let date1 = formatter.date(from: dateString1)!
let date2 = formatter.date(from: dateString2)!

let seconds = date2.timeIntervalSince(date1)
let components1 = Calendar.current.dateComponents([ .minute ], from: date1, to: date2)
let minutes = components1.minute

This gives 2177636500 for seconds and 36293941 for minutes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!