Je crée une date avec NSDateComponents()
.
let startDate = NSDateComponents()
startDate.year = 2015
startDate.month = 9
startDate.day = 1
let calendar = NSCalendar.currentCalendar()
let startDateNSDate = calendar.dateFromComponents(startDate)!
... maintenant je veux imprimer toutes les dates depuis la startDate
jusqu'à aujourd'hui, NSDate()
. J’ai déjà essayé de jouer avec NSCalendarUnit
, mais cela ne donne que la totalité de la différence, pas les dates uniques entre elles.
let unit: NSCalendarUnit = [.Year, .Month, .Day, .Hour, .Minute, .Second]
let diff = NSCalendar.currentCalendar().components(unit, fromDate: startDateNSDate, toDate: NSDate(), options: [])
Comment puis-je imprimer toutes les dates entre deux objets Date
?
Edit 2019
Entre-temps, la dénomination des classes avait changé - NSDate
est maintenant juste Date
. NSDateComponents
s'appelle maintenant DateComponents
. NSCalendar.currentCalendar()
est maintenant juste Calendar.current
.
Ajoutez simplement une unité de jour à la date jusqu'à ce qu'elle atteigne .__ la date actuelle (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: [])!
}
Mise à jour pour 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)!
}
Utilisation de l'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(), endDate: Date())
Même chose mais plus jolie:
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
}
}
Comment obtenir toutes les dates pour les 20 prochains jours:
if let date = Calendar.current.date(byAdding: .day, value: 20, to: Date()) {
print(Date().allDates(till: date))
}
J'utilise cette approche (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)!
}
}
et j'appelle ceci comme:
Dates.printDatesBetweenInterval(Dates.dateFromString("2017-01-02"), Dates.dateFromString("2017-01-9"))
La sortie est:
2017-01-02
2017-01-03
2017-01-04
2017-01-05
2017-01-06
2017-01-07
2017-01-08
2017-01-09
Voici la solution d’imprimer toutes les dates entre deux dates (code Swift 4)
var mydates : [String] = []
let startDate = "2018-03-01"
let endDate = "2018-03-05"
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: startDate)!
dateTo = fmt.date(from: endDate)!
while dateFrom <= dateTo {
mydates.append(fmt.string(from: dateFrom))
dateFrom = Calendar.current.date(byAdding: .day, value: 1, to: dateFrom)!
}
print(mydates) // Your Result
La sortie est:
["2018-03-01", "2018-03-02", "2018-03-03", "2018-03-04", "2018-03-05"]
Votre code désiré devient comme
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)
}