0

I've been developing swift iOS apps for a few months, and I'm new with dates, which I find a bit difficult. So what I want to do is to get the difference in days between two NSDate (one of them is today, and the other one is a String), and after that, get the number of days between them, and divide it with an int(dataMoneyLeft), in order to get the money per day.

Thanks for your help!

HERE'S MY CODE:

var datePassed1 : String?
var dataMoneyLeft : Int?

func getDateDifference(){
    let date = NSDate()
    let calendar = NSCalendar.currentCalendar()
    let components = calendar.components([.Day, .Month], fromDate: date)

    //let year =  components.year
    //let month = components.month
    //let day = components.day

    //-----------************-----------//

    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    let dateString = dateFormatter.dateFromString(datePassed1!)

    let calendar1: NSCalendar = NSCalendar.currentCalendar()

    // Replace the hour (time) of both dates with 00:00
    let date1 = calendar1.startOfDayForDate(dateString!)
    let date2 = calendar1.startOfDayForDate(date)

    let flags = NSCalendarUnit.Day
    let components1 = calendar.components(flags, fromDate: date1, toDate: date2, options: [])

    let finalDifference = components1.day


}
  • 1
    Possible duplicate of [Getting the difference between two NSDates in (months/days/hours/minutes/seconds)](http://stackoverflow.com/questions/27182023/getting-the-difference-between-two-nsdates-in-months-days-hours-minutes-seconds) – Shehzad Ali Feb 08 '16 at 11:36
  • That code should work, and is a better way to do it than the code posted by Simon in his answer. What is the problem you are having with your current code? – Duncan C Feb 08 '16 at 12:03

1 Answers1

1

First convert second string to Nsdate using dateformatter. Then find the difference between the two NSDates using timeIntervalSinceDate.you will get timeIntervalSinceDate as nstimeinterval.Then you can solve your problem using this difference.