我想计算月+年中两个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!)
能吗?
可以按照以下方式进行操作:
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!))
}
}
这是一种方法:
let monthsCount = Calendar.current.dateComponents([.month], from: start, to: end).month! - 1
guard monthsCount > 0 else { return [] }
return (1...monthsCount).map {
var monthYear = start
monthYear.month! += $0
let date = Calendar.current.date(from: monthYear)!
let formatter = DateFormatter()
formatter.dateFormat = "MMMM yyyy"
return formatter.string(from: date)
}
}
您应该DateComponents只将月份和年份组成部分传入此方法。您可以从这样的DateComponents对象中获取仅包含月份和年份的对象Date:```Calendar.current.dateComponents([.month, .year], from: someDate)
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。