两个日期对象之间的所有日期 (Swift)

All dates between two Date objects (Swift)

我正在使用 NSDateComponents() 创建日期。

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

...现在我想打印从 startDate 到今天 NSDate() 的所有日期。我已经尝试过 NSCalendarUnit,但它只输出整个差异,而不是两者之间的单个日期。

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

如何打印两个 Date 对象之间的所有日期?

编辑 2019

同时 类 的命名发生了变化 – NSDate 现在只是 DateNSDateComponents 现在称为 DateComponentsNSCalendar.currentCalendar() 现在只是 Calendar.current.

你想要的代码变成这样

    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)


    }

只需将日期加一天,直到到达 当前日期(Swift 2 代码):

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: [])!
}

Swift3 的更新:

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.current.date(byAdding: .day, value: 1, to: date)!
}

我正在使用这种方法 (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)!
    }
}

我这样称呼它:

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

输出为:

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

使用扩展名:

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
    }
}

用法:

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

相同但更漂亮:

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
  }
}

如何获取接下来 20 天的所有日期:

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

这里是打印两个日期之间的所有日期的解决方案(Swift 4代码)

var mydates : [String] = []
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: strstartDate)! // "2018-03-01"
dateTo = fmt.date(from: strendDate)! // "2018-03-05"


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

}

print(mydates) // Your Result

输出为:

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

您可以使用 compactMap 运算符。 我喜欢将这些功能放在扩展中,以便它们可以重用。 很难确定一个日期范围,所以我做了一个整数范围并循环遍历它。

extension Calendar {
    func getDates(_ startDate: Date, _ endDate: Date) -> [Date]  {
        // make sure parameters are valid
        guard startDate < endDate else { print("invalid parameters"); return [] }
        // how many days between dates?
        let dayDiff = Int(self.dateComponents([.day], from: startDate, to: endDate).day ?? 0)
        let rangeOfDaysFromStart: Range<Int> = 0..<dayDiff + 1
        let dates = rangeOfDaysFromStart.compactMap{ self.date(byAdding: .day, value: [=10=], to: startDate) }
        return dates
    }
}

您的用法可能是:

let startDate = Date(dateString: "1/2/2017", format: "M/d/yyyy")
let endDate = Date(dateString: "1/9/2017", format: "M/d/yyyy")
let dates = Calendar.current.getDates(startDate, endDate)
let f = DateFormatter(withFormat: "yyyy-MM-dd", locale: "us_en")
print(dates.compactMap{f.string(from: [=11=])}.joined(separator: ", "))

输出:

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