2015-09-12 41 views
10

Sto creando una data utilizzando NSDateComponents():Swift: Stampa tutte le date tra due NSDate()

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

... ora voglio stampare tutte le date dal momento che il startDate fino ad oggi, NSDate(). Ho già provato a giocare con NSCalendarUnit, ma mostra solo la differenza completa, non le singole date tra.

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

Come posso stampare tutte le date tra due NSDate?

risposta

39

Basta aggiungere un'unità al giorno per la data fino a raggiungere la data corrente (Swift 2 codice):

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

Aggiornamento per 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)! 
} 
+0

ottima soluzione, grazie! – ixany

+0

@ Martin: ricevo questo errore "L'operatore binario '<=' non può essere applicato a due operandi 'NSDate'". Mi aiuti per favore. – Smita

+0

@Smita Quale versione Xcode/Swift usi? –

1

Il codice desiderato diventa come

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) 


    } 
+0

grande soluzione troppo, ha funzionato come previsto. grazie! – ixany

1

Sto usando questo approac h (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)! 
    } 
} 

e che io chiamo questo tipo:

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

L'output è:

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

Utilizzando estensione:

extension Date{ 

func generateDatesArrayBetweenTwoDates(startDate: Date , endDate:Date) ->[Date] 
{ 
    var datesArray: [Date] = [Date]() 
    var startDate = startDate 
    let calendar = Calendar.current 

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

    while startDate <= endDate { 
     datesArray.append(startDate) 
     startDate = calendar.date(byAdding: .day, value: 1, to: startDate)! 

    } 
    return datesArray 
} 
} 

Usage:

let datesBetweenArray = Date().generateDatesArrayBetweenTwoDates(startDate: Your Start Date Object , endDate: Your End Date Object) 
0

stessa cosa, ma più bella:

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

Come per ottenere tutte le date per i prossimi 20 giorni:

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

cos'è 'startDate'? – amin

+1

@amate change Date() alla data di inizio – AlexanderZ