Gonzalo Duarte
Gonzalo Duarte

Reputation: 45

Difference between 2 NSDates, and divide the result with an Int - Swift

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


}

Upvotes: 0

Views: 238

Answers (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.

Upvotes: 1

Related Questions