我有阵列;
var mydates : [String] = []
let startDate = "2018-03-01"
let endDate = "2018-03-03"
我有3个变量,startDate
,endDate
,dates
,我想追加变量,比如;
如果startDate
= 2018-03-01,endDate
= 2018-03-03
将日期变量添加到 =" 2018-03-01,2018-03-02,2018-03-03"在开始和结束日期之间的所有日期之间。
我怎么能在swift 2中做到这一点?
答案 0 :(得分:2)
这里是打印两个日期之间的所有日期的解决方案(快速4码)
var mydates : [String] = []
let startDate = "2018-03-01"
let endDate = "2018-03-05"
var dateFrom = Date() // First date
var dateTo = Date() // Last date
// Formatter for printing the date, adjust it according to your needs:
let fmt = DateFormatter()
fmt.dateFormat = "yyy-MM-dd"
dateFrom = fmt.date(from: startDate)!
dateTo = fmt.date(from: endDate)!
while dateFrom <= dateTo {
mydates.append(fmt.string(from: dateFrom))
dateFrom = Calendar.current.date(byAdding: .day, value: 1, to: dateFrom)!
}
print(mydates) // Your Result
输出为:
["2018-03-01", "2018-03-02", "2018-03-03", "2018-03-04", "2018-03-05"]