简体   繁体   中英

Get array of dates between today and given date in Swift?

I have a date in string format, "yyyy-MM-dd" and would like to return an array of the difference in dates in that same format from today.

For example, the given date is "2019-06-29", and today's date is 2019-06-25. The returned array would contain: ["2019-06-25", "2019-06-26", "2019-06-27", "2019-06-28", "2019-06-29"].

The method I am trying to write needs to also work cross-months/years. Is something like this possible in Swift?

What I have tried: calculating the difference in dates numerically (difference of days) and adding a day to the given date until it reaches today's date. This is what brought on the issue of exceeding 30/31 days and not moving to the next months/exceeding 2019-12-31 and not moving to 2020. Surely there is a simpler concise way to achieve this result without having to write that date logic manually?

extension Formatter {
    static let date: DateFormatter = {
        let dateFormatter = DateFormatter()
        dateFormatter.calendar = Calendar(identifier: .iso8601)
        dateFormatter.locale = Locale(identifier: "en_US_POSIX")
        dateFormatter.dateFormat = "yyyy-MM-dd"
        return dateFormatter
    }()
}

extension Date {
    var noon: Date {
        return Calendar.current.date(bySettingHour: 12, minute: 0, second: 0, of: self)!
    }
}

func dates(for date: String) -> [String] {    
    // For calendrical calculations you should use noon time
    // So lets get endDate's noon time
    guard let endDate = Formatter.date.date(from: date)?.noon else { return [] }
    // then lets get today's noon time
    var date = Date().noon
    var dates: [String] = []
    // while date is less than or equal to endDate
    while date <= endDate {
        // add the formatted date to the array
        dates.append( Formatter.date.string(from: date))
        // increment the date by one day
        date = Calendar.current.date(byAdding: .day, value: 1, to: date)!
    }
    return dates
}

dates(for: "2019-06-29")  // ["2019-06-25", "2019-06-26", "2019-06-27", "2019-06-28", "2019-06-29"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM