All dates between two Date objects (Swift)

情到浓时终转凉″ 提交于 2020-01-08 12:30:27

问题


I’m creating a date using NSDateComponents().

let startDate = NSDateComponents()
startDate.year = 2015
startDate.month = 9
startDate.day = 1
let calendar = NSCalendar.currentCalendar()
let startDateNSDate = calendar.dateFromComponents(startDate)!

... now I want to print all dates since the startDate until today, NSDate(). I’ve already tried playing with NSCalendarUnit, but it only outputs the whole difference, not the single dates between.

let unit: NSCalendarUnit = [.Year, .Month, .Day, .Hour, .Minute, .Second]
let diff = NSCalendar.currentCalendar().components(unit, fromDate: startDateNSDate, toDate: NSDate(), options: [])

How can I print all dates between two Dateobjects?

Edit 2019

In the meantime the naming of the classes had changed – NSDate is now just Date. NSDateComponents is now called DateComponents. NSCalendar.currentCalendar() is now just Calendar.current.


回答1:


Just add one day unit to the date until it reaches the current date (Swift 2 code):

var date = startDateNSDate // first date
let endDate = NSDate() // last date

// Formatter for printing the date, adjust it according to your needs:
let fmt = NSDateFormatter()
fmt.dateFormat = "dd/MM/yyyy"

// While date <= endDate ...
while date.compare(endDate) != .OrderedDescending {
    print(fmt.stringFromDate(date))
    // Advance by one day:
    date = calendar.dateByAddingUnit(.Day, value: 1, toDate: date, options: [])!
}

Update for Swift 3:

var date = startDate // first date
let endDate = Date() // last date

// Formatter for printing the date, adjust it according to your needs:
let fmt = DateFormatter()
fmt.dateFormat = "dd/MM/yyyy"

while date <= endDate {
    print(fmt.string(from: date))
    date = calendar.date(byAdding: .day, value: 1, to: date)!
}



回答2:


Using extension:

extension Date {
    static func dates(from fromDate: Date, to toDate: Date) -> [Date] {
        var dates: [Date] = []
        var date = fromDate

        while date <= toDate {
            dates.append(date)
            guard let newDate = Calendar.current.date(byAdding: .day, value: 1, to: date) else { break }
            date = newDate
        }
        return dates
    }
}

Usage:

let datesBetweenArray = Date.dates(from: Date(), endDate: Date())



回答3:


Same thing but prettier:

extension Date {

  func allDates(till endDate: Date) -> [Date] {
    var date = self
    var array: [Date] = []
    while date <= endDate {
      array.append(date)
      date = Calendar.current.date(byAdding: .day, value: 1, to: date)!
    }
    return array
  }
}

How to get all dates for next 20 days:

if let date = Calendar.current.date(byAdding: .day, value: 20, to: Date()) {
  print(Date().allDates(till: date))
}



回答4:


Your desired code becomes like

    let startDate = NSDateComponents()
    startDate.year = 2015
    startDate.month = 9
    startDate.day = 1
    let calendar = NSCalendar.currentCalendar()
    let startDateNSDate = calendar.dateFromComponents(startDate)!


    var offsetComponents:NSDateComponents = NSDateComponents();
    offsetComponents.day = 1
    var nd:NSDate = startDateNSDate;

    println(nd)
    while nd.timeIntervalSince1970 < NSDate().timeIntervalSince1970 {
        nd = calendar.dateByAddingComponents(offsetComponents, toDate: nd, options: nil)!;
            println(nd)


    }



回答5:


I am using this approach (Swift 3):

import Foundation

class Dates {
    static func printDatesBetweenInterval(_ startDate: Date, _ endDate: Date) {
        var startDate = startDate
        let calendar = Calendar.current

        let fmt = DateFormatter()
        fmt.dateFormat = "yyyy-MM-dd"

        while startDate <= endDate {
            print(fmt.string(from: startDate))
            startDate = calendar.date(byAdding: .day, value: 1, to: startDate)!
        }
    }

    static func dateFromString(_ dateString: String) -> Date {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"

        return dateFormatter.date(from: dateString)!
    }
}

and I am calling this like:

Dates.printDatesBetweenInterval(Dates.dateFromString("2017-01-02"), Dates.dateFromString("2017-01-9"))

The output is:

2017-01-02
2017-01-03
2017-01-04
2017-01-05
2017-01-06
2017-01-07
2017-01-08
2017-01-09



回答6:


Here is Solution of Print all dates between two Dates (Swift 4 Code)

var mydates : [String] = []
let startDate = "2018-03-01"
let endDate   = "2018-03-05"

var dateFrom =  Date() // First date
var dateTo = Date()   // Last date

// Formatter for printing the date, adjust it according to your needs:
let fmt = DateFormatter()
fmt.dateFormat = "yyy-MM-dd"
dateFrom = fmt.date(from: startDate)!
dateTo = fmt.date(from: endDate)!


while dateFrom <= dateTo {
    mydates.append(fmt.string(from: dateFrom))
    dateFrom = Calendar.current.date(byAdding: .day, value: 1, to: dateFrom)!

}

print(mydates) // Your Result

Output is:

["2018-03-01", "2018-03-02", "2018-03-03", "2018-03-04", "2018-03-05"]


来源:https://stackoverflow.com/questions/32536612/all-dates-between-two-date-objects-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!