如何在Swift中获取两个日期之间的天数? [英] How to get an array of days between two dates in Swift?
本文介绍了如何在Swift中获取两个日期之间的天数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请考虑我们具有以下函数签名:
Consider that we have a function signature as:
func datesRange(from: Date, to: Date) -> [Date]
应从开始使用
和
至
日期实例,并返回一个数组,其中包含其参数之间的日期(天)。
which should take from
date and to
date instances and returns an array containing the dates (days) between its parameters. How to achieve it?
推荐答案
您可以这样实现:
func datesRange(from: Date, to: Date) -> [Date] {
// in case of the "from" date is more than "to" date,
// it should returns an empty array:
if from > to { return [Date]() }
var tempDate = from
var array = [tempDate]
while tempDate < to {
tempDate = Calendar.current.date(byAdding: .day, value: 1, to: tempDate)!
array.append(tempDate)
}
return array
}
用法:
let today = Date()
let nextFiveDays = Calendar.current.date(byAdding: .day, value: 5, to: today)!
let myRange = datesRange(from: today, to: nextFiveDays)
print(myRange)
/*
[2018-03-20 14:46:03 +0000,
2018-03-21 14:46:03 +0000,
2018-03-22 14:46:03 +0000,
2018-03-23 14:46:03 +0000,
2018-03-24 14:46:03 +0000,
2018-03-25 14:46:03 +0000]
*/
这篇关于如何在Swift中获取两个日期之间的天数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文