gpt4 book ai didi

swift - 获取日期之间的月份列表

转载 作者:行者123 更新时间:2023-11-28 12:06:01 27 4
gpt4 key购买 nike

我有两个日期,即 2/02/201619/03/2018

我正在尝试获取这些日期之间的月份和年份

输出应该是

Feb 2016, Mar 2016 ......and so on.... Jan 2018, Feb 2018, Mar 2018.

试过月份Gap码-

  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

最佳答案

这是一个简单的方法,可以按照您上面描述的格式返回日期和月份,

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")

关于swift - 获取日期之间的月份列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49361425/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com