ios - 在 Swift 中迭代日期范围的最有效方法是什么?

标签 ios swift

我正在构建一个 Swift 习惯养成应用程序。在某个时刻,用户选择他们想要养成的习惯的持续时间(以天为单位)。用户还可以选择他们想在一周中的哪几天练习(星期日、星期一、星期二等)。开始日期是他们养成习惯的那一天。

我目前有开始日期和结束日期(基于用户选择的天数)。但是,在该日期范围内,我需要提取用户选择的特定日期的日期。

我的想法是,对于时间间隔(开始日期、结束日期)内的每个工作日值“x”,返回日历日期。但是,我已经尝试创建一个 DateInterval,但我无法对其进行迭代,因为它不符合协议(protocol)“序列”。

是否有一种有效的方法来迭代这个日期范围并提取这些其他日期?有没有我还没有想到的更好的方法?

下面是我当前的日期起始代码:

var date = Date()
var duration = 10
let calendar = Calendar.current

let dateEnding = Calendar.current.date(byAdding: .day, value: duration, to: date as Date)!

//Returns a number representing day of the week.  i.e. 1 = Sunday
let weekDay = calendar.component(.weekday, from: date)


//Initializing a time interval, based on user selected duration and start date
let timeInterval = DateInterval.init(start: date, end: dateEnding)

感谢您的帮助...

最佳答案

我们可以利用Strideable协议(protocol)的力量:

extension Date: Strideable {
    public func distance(to other: Date) -> TimeInterval {
        return other.timeIntervalSinceReferenceDate - self.timeIntervalSinceReferenceDate
    }

    public func advanced(by n: TimeInterval) -> Date {
        return self + n
    }
}

然后在你的函数中:

// Iterate by 1 day
// Feel free to change this variable to iterate by week, month etc.
let dayDurationInSeconds: TimeInterval = 60*60*24
for date in stride(from: startDate, to: endDate, by: dayDurationInSeconds) {
    print(date)
}

输出:

2018-07-19 12:18:07 +0000
2018-07-20 12:18:07 +0000
2018-07-21 12:18:07 +0000
2018-07-22 12:18:07 +0000
2018-07-23 12:18:07 +0000
....

代码取自this proposal

关于ios - 在 Swift 中迭代日期范围的最有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46857393/

相关文章:

iphone - CGRect 中的 presentModalViewController

c++ - iOS 上的 OpenCV 对象检测 (HOGDescriptor)

ios - 从 parse.com 中提取数据,但它根本没有显示在 ios 的 UITableView 中(swift)

ios - 为什么 UIBarButtonItem 显示为已禁用?

ios - 按高度比例放置uiview,如何?

ios - Swift Collcetionview didSelectItemAtIndexPath 不起作用

ios - SwiftUI:当应用程序在后台时如何添加带有应用程序 Logo 的模糊 View ?

ios - 在变量上使用 POP 时,类没有初始值设定项

ios - Flexbox 方向改变宽度/高度问题

swift - 为什么在 swift 5 迁移后 IBOutlets 是可选的