简体   繁体   English

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

[英]All dates between two Date objects (Swift)

I'm creating a date using NSDateComponents() .我正在使用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() . ...现在我想打印从startDate到今天的所有日期NSDate() I've already tried playing with NSCalendarUnit , but it only outputs the whole difference, not the single dates between.我已经尝试过使用NSCalendarUnit ,但它只输出整个差异,而不是之间的单个日期。

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 Date objects?如何打印两个Date对象之间的所有日期?

Edit 2019编辑 2019

In the meantime the naming of the classes had changed – NSDate is now just Date .与此同时,类的命名发生了变化—— NSDate现在只是Date NSDateComponents is now called DateComponents . NSDateComponents现在被称为DateComponents NSCalendar.currentCalendar() is now just Calendar.current . NSCalendar.currentCalendar()现在只是Calendar.current

Just add one day unit to the date until it reaches the current date (Swift 2 code):只需在日期中添加一个天单位,直到它到达当前日期(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: [])!
}

Update for Swift 3: 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)!
}

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(), to: Date())

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:如何获取接下来 20 天的所有日期:

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

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)


    }

Here is Solution of Print all dates between two Dates (Swift 4 Code)这是打印两个日期之间的所有日期的解决方案(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

Output is:输出是:

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

I am using this approach (Swift 3):我正在使用这种方法(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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM