如何得到两个日期之间的总月数? 这是获得约会的正常方式
1) 开始日期:2020-2-22 10:25:00
2) 结束日期:2020-3-3 12:34:00
let diffInDate:Int = Calendar.current.dateComponents([.month], from: startDate, to: endDate).month!
如果我们按照上面给定的日期进行检查,它将返回 0,因为总共不到 30 天。
现在我想要结果有一个月的差异,如果我们检查上面的日期,它应该返回 1,因为月份改变了。那么有什么方法可以检查包括那个月在内的日期差异吗?
最佳答案
正如您正确识别的那样,dateComponents(_:from:to:)
不计算小数月份。
但是,有another overload ,计算 DateComponents
而不是 Date
之间的差异。我们可以从开始和结束 Date
中去掉我们不需要的所有内容(天、小时、分钟等),将它们传递给这个重载,它应该为我们进行计算。这类似于在减去 float 之前对其进行舍入,以便您可以获得它们的整数部分之间的差值。
let startDateComponents = Calendar.current.dateComponents([.year, .month], from: startDate)
let endDateComponents = Calendar.current.dateComponents([.year, .month], from: endDate)
let diffInDate = Calendar.current.dateComponents([.month], from: startDateComponents, to: endDateComponents).month!
请注意,我们还获得了开始日期和结束日期的 year
部分,因为计算中也需要年份。但是当我们计算差异时,我们只想要 month
。
关于ios - 获取总数包括 2 个日期之间的月份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60500764/