Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IOS Swift. Time since date

I want the number of months and days since a given date which is given by a string.

d is a string of a date

    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "MM-dd-yy"
    let date = dateFormatter.dateFromString(d)
    startTime = date?.timeIntervalSinceReferenceDate

I would ideally like the months,days,minutes since the date but I will work that part once I get passed this error. The compiler is complaining about the last line.

Thanks

like image 224
SJP Avatar asked Jan 05 '15 23:01

SJP


1 Answers

You need to use an NSCalendar to compute a difference in terms of months and days. Example:

let calendar = NSCalendar.autoupdatingCurrentCalendar()
calendar.timeZone = NSTimeZone.systemTimeZone()
let dateFormatter = NSDateFormatter()
dateFormatter.timeZone = calendar.timeZone
dateFormatter.dateFormat = "yyyy-MM-dd"
if let startDate = dateFormatter.dateFromString("2014-9-15") {
    let components = calendar.components([ .Month, .Day ],
        fromDate: startDate, toDate: NSDate(), options: [])
    let months = components.month
    let days = components.day
    print("It's been \(months) months and \(days) days.")
}

Output (on 2014-01-05):

It's been 3 months and 21 days.
like image 142
rob mayoff Avatar answered Sep 21 '22 12:09

rob mayoff