Home Ask Login Register

Developers Planet

Your answer is one click away!

Gonzalo Duarte February 2016

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!


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



Rajesh R February 2016

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.

Post Status

Asked in February 2016
Viewed 3,247 times
Voted 8
Answered 1 times


Leave an answer

Quote of the day: live life