Subtract dates in swift

0

I need to subtract two dates and get the number of days that pass from one to another.

I have this code in which I get the fields of the date, so I can put it in any format:

let arrayFechaDesde = AppDelegate().explode(caracter: " ", cadena: fechaDesde)
let arrayFechaDesdeDos = AppDelegate().explode(caracter: " ", cadena: arrayFechaDesde[1])
let dayDesde = arrayFechaDesdeDos[0]
let monthDesde = arrayFechaDesdeDos[1]
let yearDesde = arrayFechaDesdeDos[2]

let arrayFechaHasta = AppDelegate().explode(caracter: " ", cadena: fechaHasta)
let arrayFechaHastaDos = AppDelegate().explode(caracter: " ", cadena: arrayFechaHasta[1])
let dayHasta = arrayFechaHastaDos[0]
let monthHasta = arrayFechaHastaDos[1]
let yearHasta = arrayFechaHastaDos[2]

The variable fechaDesde and fechaHasta have this format: 11/10/2016 08:00

How can I subtract both dates to get the number of days that have passed from one to the other?

    
asked by 09.11.2016 в 10:33
source

1 answer

2

To subtract both dates you do not need to separate in a day, month, year arrangement.

In swift you have the object of type NSCalendar that basically in your documentation says:

NSCalendar English Documentation

  

NSCalendar are objects that encapsulate information about time calculations ...

We create an object NSCalendar

let calendar = NSCalendar.currentCalendar()

Then we created

let fecha_desde = calendar.startOfDayForDate(fechaDesde)
let fecha_hasta = calendar.startOfDayForDate(fechaHasta)

This method startOfDayForDate returns the date and ignores the time that your date has. Why do we do this? Because if you want to know exactly the difference in days between two dates you should ignore the hours because this can return 0 if 24 hours have not elapsed between one date and another. p>

Then

let dias= NSCalendarUnit.Day

We create a variable of type NSCalendarUnit.Day that specifies calendar units in this case as we want days, we say Day

let result = calendar.components(dias, fromDate: fecha_desde , toDate: fecha_hasta, options: [])

The function calendar.components allows us to calculate the difference between one date and another and in the unit that we want, in this case dias

And finally we get

result.day

What is the difference between the two dates in dias

EDIT

Swift 3 apparently does not work with NSCalendar instead it takes Calendar

dataComponents swift

In place to swift 3:

let dias= Set<Calendar.Component>([.day])
let result = calendar.dateComponents(dias, from: fechaDesde as   Date,  to: fechaHasta as Date)
result.day
    
answered by 09.11.2016 / 13:12
source