首页 文章

FSCalendar:如何在两个日期获取日期?

提问于
浏览
3

我正在使用Swift 3,我想在两个日期之间每天打印一次 .

例如:

08-10-2017 - >开始日期

08-15-2017 - >结束日期

应打印:

08-10-2017 08-11-2017 08-12-2017 08-13-2017 08-14-2017 08-15-2017

我希望在两个具体日期获得范围,有人可以帮助我 . 我试着将这两个日期用于循环,但没有机会 .

1 回答

  • 3

    您需要创建基于日历的日期,并开始增加开始日期,直到您到达结束日期 . 这是一段代码片段,如何做到:

    func showRange(between startDate: Date, and endDate: Date) {
        // Make sure startDate is smaller, than endDate
        guard startDate < endDate else { return }
    
        // Get the current calendar, i think in your case it should some fscalendar instance
        let calendar = Calendar.current
        // Calculate the endDate for your current calendar
        let calendarEndDate = calendar.startOfDay(for: endDate)
    
        // Lets create a variable, what we can increase day by day
        var currentDate = calendar.startOfDay(for: startDate)
    
        // Run a loop until we reach the end date
        while(currentDate <= calendarEndDate) {
            // Print the current date
            print(currentDate)
            // Add one day at the time
            currentDate = Calendar.current.date(byAdding: .day, value: 1, to: currentDate)!      
        }
    }
    

    Usage:

    let today = Date()
    let tenDaysLater = Calendar.current.date(byAdding: .day, value: 10, to: today)!
    showRange(between: today, and: tenDaysLater)
    

相关问题