小编典典

两个Date对象之间的所有日期(快速)

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


阅读 291

收藏
2020-07-07

共1个答案

小编典典

只需在日期中添加一天单位,直到达到当前日期(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: [])!
}

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