使用 Cocoa 确定两个日期之间的月数
如何使用 Cocoa 计算两个日期之间的月数?
谢谢, 斯坦
How do I calculate the number of months between two dates using Cocoa?
Thanks,
Stan
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
如何使用 Cocoa 计算两个日期之间的月数?
谢谢, 斯坦
How do I calculate the number of months between two dates using Cocoa?
Thanks,
Stan
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(6)
查看 NSCalendars
Look at NSCalendars components:fromDate:toDate:options method. It allows you to subtract dates and then extract the months property value
要获得包含一个月的一部分的答案,可以使用以下命令:
To get an answer that includes the fraction of a month the following can be used:
我必须计算两个日期之间的月份变化。这意味着从 1 月 31 日到 2 月 1 日已经过去了 1 个月,
NSCalendar.components
将返回 0。I had to calculate the months changes between two dates. This means that from the 31st of January to the 1st of February 1 month has passed were
NSCalendar.components
will return 0.对于以下示例,组件:fromDate:toDate:选项无法正常工作:
开始日期:2012 年 1 月 1 日
结束日期:2012 年 3 月 31 日。
使用上述方法的月份数 = 2
正确答案应该是 3 个月。
我使用长计算方式如下:
1. 找出起始月份的天数。将其添加到月份的小数部分。如果第一个日期是月初,则将其计为整月。
2. 求最后一个月的天数。将其添加到月份的小数部分如果日期是该月的最后一天,则将其视为完整月份。
3. 找到 2 个日期之间的整个/完整月份并添加到月份的整数部分。
4. 添加整数 &月份的小数部分以获得正确的值。
components:fromDate:toDate:options doesn't work correctly for following example:
begin date: Jan 01, 2012
end date: March 31, 2012.
num of months using above method = 2
The correct answer should be 3 months.
I am using the long way of calculations as follows:
1. Find number of days in the beginning month. Add it to the fraction part of the month. If the first date is the beginning of the month, count it as full month.
2. find the number of days in the end month. Add it to the fraction part of the monthIf the date is the last of the month count it as a full month.
3. Find the whole/full months between the 2 dates and add to the integer part of the month.
4. Add the integer & fraction parts of the months to get a correct value.
这是针对 iOS11 更新的 @eliocs 答案的 Objective-C 版本:
Here's the objective-c version of @eliocs answer updated for iOS11: