获取日期之间的月份列表
Posted
技术标签:
【中文标题】获取日期之间的月份列表【英文标题】:Get list of months between dates 【发布时间】:2018-03-19 11:03:22 【问题描述】:我有两个日期,即 2/02/2016 和 19/03/2018
我正在尝试获取此日期之间的月份和年份
输出应该是
2016 年 2 月、2016 年 3 月......等等...... 2018 年 1 月、2018 年 2 月、2018 年 3 月。
尝试过的月差代码 -
let date1 = DateComponents(calendar: .current, year: 2016, month: 2, day: 2).date!
let date2 = DateComponents(calendar: .current, year: 2018, month: 3, day: 19).date!
let monthGap = Calendar.current.dateComponents([.month], from: date1, to: date2)
print("monthGap is \(String(describing: monthGap.month))")//prints monthGap is 25
【问题讨论】:
How to get month name with year and list of years between two Date的可能重复 【参考方案1】:这是一个简单的方法,可以按照上述格式返回日期和月份,
func getMonthAndYearBetween(from start: String, to end: String) -> [String]
let format = DateFormatter()
format.dateFormat = "dd/MM/yyyy"
guard let startDate = format.date(from: start),
let endDate = format.date(from: end) else
return []
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents(Set([.month]), from: startDate, to: endDate)
var allDates: [String] = []
let dateRangeFormatter = DateFormatter()
dateRangeFormatter.dateFormat = "MMM yyyy"
for i in 0 ... components.month!
guard let date = calendar.date(byAdding: .month, value: i, to: startDate) else
continue
let formattedDate = dateRangeFormatter.string(from: date)
allDates += [formattedDate]
return allDates
你这样称呼它,
getMonthAndYearBetween(from: "2/02/2016", to: "19/03/2018")
【讨论】:
【参考方案2】:斯威夫特 5
根据 Sandeep 的回答,此函数接受 Date
对象作为输入,并将返回一个 Date
对象数组:
extension Date
static func getMonthAndYearBetween(from start: Date, to end: Date) -> [Date]
var allDates: [Date] = []
guard start < end else return allDates
let calendar = Calendar.current
let month = calendar.dateComponents([.month], from: start, to: end).month ?? 0
for i in 0...month
if let date = calendar.date(byAdding: .month, value: i, to: start)
allDates.append(date)
return allDates
【讨论】:
以上是关于获取日期之间的月份列表的主要内容,如果未能解决你的问题,请参考以下文章