Skip to content

Instantly share code, notes, and snippets.

@EliaCereda
Last active April 17, 2016 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EliaCereda/5b634bec1f080e63582245894fd870f9 to your computer and use it in GitHub Desktop.
Save EliaCereda/5b634bec1f080e63582245894fd870f9 to your computer and use it in GitHub Desktop.
func relativeDateString(date: NSDate) -> String {
let components: Array<(Int, (Int) -> String)> = [
(60 * 60 * 24 * 365, { x in "\(x) anni fa" }),
(60 * 60 * 24 * 30, { x in "\(x) mesi fa" }),
(60 * 60 * 24 , { x in "\(x) giorni fa" }),
(60 * 60 , { x in "\(x) ore fa" }),
(60 , { x in "\(x) minuti fa" })
]
let timeInterval = Int(NSDate().timeIntervalSinceDate(date))
for (secondsPerComponent, formatString) in components {
let componentUnits = timeInterval / secondsPerComponent
if componentUnits != 0 {
return formatString(componentUnits)
}
}
return "alcuni secondi fa"
}
func relativeDateString(date: NSDate) -> String {
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.WeekOfYear, .Day, .Hour, .Minute], fromDate: date, toDate: NSDate(), options: [])
if components.weekOfYear > 0 { // More than 7 days
return Utility.dateFormattedEuropeMode(date)
} else if components.day > 0 { // This week
if components.day > 1 { // More than 1 day
return "\(components.day) \(Utility.localizedString("DAYS_AGO"))"
} else { // Yesterday
return Utility.localizedString("YESTERDAY")
}
} else { // Today
if components.hour > 1 { // From 2 to 23 hours
return "\(components.hour) \(Utility.localizedString("HOURS_AGO"))"
} else {
if components.hour == 1 { // 1 hour
return "\(components.hour) \(Utility.localizedString("HOUR_AGO"))"
} else {
if components.minute > 5 { // From 5 to 59 minutes
return "\(components.minute) \(Utility.localizedString("MINUTES_AGO"))"
} else { // Less than 5 minutes
return Utility.localizedString("NOW")
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment