restar fechas fecha actual swift nsdate nsdateformatter nscalendar nsdatecomponents

fechas - string to date swift



Swift: imprime todas las fechas entre dos NSDate() (5)

Estoy creando una fecha usando NSDateComponents() :

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

... ahora quiero imprimir todas las fechas desde el día de startDate hasta el día de hoy, NSDate() . Ya intenté jugar con NSCalendarUnit, pero solo muestra la diferencia completa, no las fechas individuales entre.

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

¿Cómo puedo imprimir todas las fechas entre dos NSDates?


Tu código deseado se vuelve como

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


Simplemente agregue una unidad de un día a la fecha hasta que llegue a la fecha actual (código 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: [])! }

Actualización para 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)! }


Estoy usando este enfoque (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)! } }

y lo llamo así:

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

El resultado es:

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


Usando la extensión:

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

Uso:

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


Lo mismo pero más bonito:

extension Date { func allDates(till endDate: Date) -> [Date] { var date = self var array: [Date] = [] while date <= endDate { array.append(startDate) date = Calendar.current.date(byAdding: .day, value: 1, to: startDate)! } return array } }

Cómo obtener todas las fechas para los próximos 20 días:

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