How to add days to a date in swift 3

后端 未结 2 1914
南笙
南笙 2021-01-17 10:23

I am getting number of days,Start date and end date from a service. I want to get the list of all dates in between start date and end date. Let\'s say my start date is 2017/

2条回答
  •  无人及你
    2021-01-17 10:55

    A simple while loop will get you what you need. Example:

    func generateDates(startDate :Date?, addbyUnit:Calendar.Component, value : Int) -> [Date] {
    
        var dates = [Date]()
        var date = startDate!
        let endDate = Calendar.current.date(byAdding: addbyUnit, value: value, to: date)!
        while date < endDate {
            date = Calendar.current.date(byAdding: addbyUnit, value: 1, to: date)!
            dates.append(date)
        }
        return dates
    }
    

    Edit: Or you can change your implementation slightly if you get your end date in advance

    func generateDates(between startDate: Date?, and endDate: Date?, byAdding: Calendar.Component) -> [Date] {
    
        var dates = [Date]()
        guard var date = startDate, let endDate = endDate else {
            return []
        }
        while date < endDate {
            date = Calendar.current.date(byAdding: byAdding, value: 1, to: date)!
            dates.append(date)
        }
        return dates
    }
    

提交回复
热议问题