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

问题描述 投票:0回答:8

我正在使用

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
现在只是
Date
NSDateComponents
现在称为
DateComponents
NSCalendar.currentCalendar()
现在只是
Calendar.current

swift nsdate nsdateformatter nscalendar nsdatecomponents
8个回答
67
投票

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

48
投票

使用扩展:

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())

9
投票

同样的东西,但更漂亮:

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

4
投票

这是打印两个日期之间的所有日期的解决方案(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"]

3
投票

你想要的代码变成这样

    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)


    }

2
投票

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

2
投票

您可以使用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: $0, 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: $0)}.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"

0
投票
let easy = DateInterval(start: date1, end: date2).days

let extended = Calendar.current.dateInterval(year: 2025, month: 5).days
extension DateInterval {

var days: [Date] {
    let calendar = Calendar.current
    let days = calendar.dateComponents([.day], from: start, to: end).day ?? 0
    return Array(0...days).compactMap {
        calendar.date(byAdding: .day, value: $0, to: start)
    }
}}
请添加到当前函数的实现中,如何写得更好,也许:
extension Calendar {

func dateInterval(year: Int, month: Int?, extendedToWeek: Bool = false) -> DateInterval? {
    guard
        var start = date(from: DateComponents(year: year, month: month)),
        var interval = dateInterval(of: month != nil ? .month : .year, for: start),
        var end = date(byAdding: .day, value: -1, to: interval.end)
    else { return nil }
    
    if extendedToWeek {
        let component: Calendar.Component = month != nil ? .weekOfMonth : .weekOfYear
        start = dateInterval(of: component, for: start)?.start ?? start
        interval = dateInterval(of: component, for: end) ?? interval
        end = date(byAdding: .day, value: -1, to: interval.end) ?? end
    }
    return DateInterval(start: start, end: end)
}}
简单日历的间隔与周对齐。 (延长至一周:)

© www.soinside.com 2019 - 2024. All rights reserved.