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?
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
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.
Asked in February 2016Viewed 3,247 timesVoted 8Answered 1 times