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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With