IOS Swift Time from date

I need the number of months and days from the date given by the string.

d - date string

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

Ideally, I would like a month, days, minutes from the date, but I will work on this part as soon as I get this error. The compiler complains about the last line.

thanks

+5
source share
1 answer

You need to use NSCalendar to calculate the 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 been \(months) months and \(days) days.") } 

Output (2014-01-05):

 It been 3 months and 21 days. 
+7
source

Source: https://habr.com/ru/post/1210431/


All Articles