快速获取2个日期之间的总包含月份 [英] Get total include months between 2 date in swift

查看:43
本文介绍了快速获取2个日期之间的总包含月份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获得两个日期之间的总月数?这是获取日期的常规方法

how to get a total month between 2 dates? here is the normal way to get a date

1)开始日期:2020-2-22 10:25:00

1) startDate: 2020-2-22 10:25:00

2)结束日期:2020-3-3 12:34:00

2) endDate: 2020-3-3 12:34:00

let diffInDate:Int = Calendar.current.dateComponents([.month], from: startDate, to: endDate).month!

如果我们按照上述日期进行检查,由于总共30天,它将返回0.

if we check as per the above-given date it will return 0 due to not total 30 days.

现在,如果我们检查上述日期,我希望结果有一个月差,因为月份改变,它应该返回1.所以有什么办法可以检查包括该月在内的日期差异?

now I want the result with a month difference if we check the above date it should return 1 because the month changes. so is there any way to check date difference including that month?

推荐答案

您已正确识别 dateComponents(_:from:to:)不计算小数月份.

As you have correctly identified dateComponents(_:from:to:) doesn't count the fractional months.

但是,有另一个重载,可以计算出差异在 DateComponents 之间而不是在 Date 之间.我们可以从开始和结束日期 Date 中删除不需要的所有内容(日期,小时,分钟等),将它们传递给此重载,它应该为我们进行计算.这类似于在将浮点数相减之前对其进行四舍五入,以便获得它们的整数部分之间的差.

However, there is another overload, that computes the difference between DateComponents instead of Dates. We can strip off everything we don't need (day, hour, minute etc) from the start and end Dates, pass them into this overload, and it should do the calculation for us. This is analogous to rounding floating point numbers before subtracting them, so that you can get the difference between their integer parts.

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 .

Notice that we get the year component of the start and end dates as well, because the year is needed in the calculation as well. But when we calculate the difference, we only want the month.

这篇关于快速获取2个日期之间的总包含月份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆