I have my created_at in String (in form of 2015-12-16 19:28:16
). I want to compare it to the current time and give time difference in a form of 5h
, 35m
, 3d
etc...
I have found on a SO answer that I can use an extension to achieve that. This is the extension:
extension NSDate {
func yearsFrom(date:NSDate) -> Int{
return NSCalendar.currentCalendar().components(.Year, fromDate: date, toDate: self, options: []).year
}
func monthsFrom(date:NSDate) -> Int{
return NSCalendar.currentCalendar().components(.Month, fromDate: date, toDate: self, options: []).month
}
func weeksFrom(date:NSDate) -> Int{
return NSCalendar.currentCalendar().components(.WeekOfYear, fromDate: date, toDate: self, options: []).weekOfYear
}
func daysFrom(date:NSDate) -> Int{
return NSCalendar.currentCalendar().components(.Day, fromDate: date, toDate: self, options: []).day
}
func hoursFrom(date:NSDate) -> Int{
return NSCalendar.currentCalendar().components(.Hour, fromDate: date, toDate: self, options: []).hour
}
func minutesFrom(date:NSDate) -> Int{
return NSCalendar.currentCalendar().components(.Minute, fromDate: date, toDate: self, options: []).minute
}
func secondsFrom(date:NSDate) -> Int{
return NSCalendar.currentCalendar().components(.Second, fromDate: date, toDate: self, options: []).second
}
func offsetFrom(date:NSDate) -> String {
if yearsFrom(date) > 0 { return "\(yearsFrom(date))y" }
if monthsFrom(date) > 0 { return "\(monthsFrom(date))M" }
if weeksFrom(date) > 0 { return "\(weeksFrom(date))w" }
if daysFrom(date) > 0 { return "\(daysFrom(date))d" }
if hoursFrom(date) > 0 { return "\(hoursFrom(date))h" }
if minutesFrom(date) > 0 { return "\(minutesFrom(date))m" }
if secondsFrom(date) > 0 { return "\(secondsFrom(date))s" }
return ""
}
}
So I can use dateWithEra()
and call offsetFrom()
:
let date4 = NSCalendar.currentCalendar().dateWithEra(1, year: 2015, month: 11, day: 28, hour: 5, minute: 9, second: 0, nanosecond: 0)!
let timeOffset3 = NSDate().offsetFrom(date3) // "54m"
However, I want to give it a date in String.
let myDate = post!["created_at"].string! // 2015-12-16 19:28:16
How can I give it a String to be able to convert 3h
, 30m
? I think I can exploit the string and place it in dateWithEra, but is there a way of giving it a string directly?
Or am I completely out of track? What I want to achieve is getting the time difference between a date in a string (in 2015-12-16 19:28:16 format) and current time and present it as "5h"
or "50m"
.