如何在 Swift 中获取两个日期之间的天数? [复制]
Posted
技术标签:
【中文标题】如何在 Swift 中获取两个日期之间的天数? [复制]【英文标题】:How to get an array of days between two dates in Swift? [duplicate] 【发布时间】:2018-03-20 14:48:08 【问题描述】:假设我们有一个函数签名:
func datesRange(from: Date, to: Date) -> [Date]
它应该采用from
日期和to
日期实例,并返回一个包含其参数之间的日期(天)的数组。如何实现?
【问题讨论】:
相关:Swift: Print all dates between two NSDate(). 【参考方案1】:你可以这样实现它:
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 中获取两个日期之间的天数? [复制]的主要内容,如果未能解决你的问题,请参考以下文章