我必须计算两个NSDate在月+年之间的时间。
例1:
Start Date: September 2018
End Date: May 2019
因此,我必须了解这两个日期之间的区别,只需显示最后6个月,如下所示:
April 2019
March 2019
February 2019
January 2019
December 2018
November 2018
例2:
Start Date: October 2019
End Date: December 2019```
产出应是:
November 2019 October 2019
使用下面的代码,我可以在几个月内得到两个日期之间的区别:
let components = Calendar.current.dateComponents([.weekOfYear, .month], from: subscriptionDate!, to: currentDate!)
有人能帮我吗?
谢谢!
你可以这样做.
//set start & end date in correct format
let strStartDate = "September 2019"
let strEndDate = "December 2019"
//create date formatter
let formatter = DateFormatter()
formatter.dateFormat = "MMMM yyyy"
//convert string into date object
guard let startDate = formatter.date(from: strStartDate) else {
print("invalid start date")
return
}
//convert string into date object
guard let endDate = formatter.date(from: strEndDate) else {
print("invalid end date time")
return
}
//calculate the month from end date and that should not exceed the start date
for month in 1...6 {
if let dt = Calendar.current.date(byAdding: .month, value: -month, to: endDate) {
if dt.compare(startDate) == .orderedAscending {
break
}
print(formatter.string(from: dt!))
}
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。