Created
March 14, 2017 16:33
-
-
Save DigitalLeaves/1d456ca6d65290369b9d2ed6323c9784 to your computer and use it in GitHub Desktop.
A quick and dirty way to get an approximate, relative date from a date.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
extension Date { | |
func quickRelativeTime() -> String { | |
let then = self.timeIntervalSince1970 | |
let now = Date().timeIntervalSince1970 | |
let seconds = now - then | |
if seconds < 0 { return "Sometime in the future..." } | |
let minutes = round(seconds/60) | |
let hours = round(minutes/60) | |
let days = round(hours/24) | |
let weeks = round(days/7) | |
let months = round(days/30) | |
if seconds < 10 { return "Just now" } else if seconds < 60 { return "\(Int(seconds)) seconds ago" } | |
if minutes < 60 { | |
if minutes == 1 { return "A minute ago" } else { return "\(Int(minutes)) minutes ago" } | |
} | |
if hours < 24 { | |
if hours == 1 { return "An hour ago" } else { return "\(Int(hours)) hours ago" } | |
} | |
if days < 7 { | |
if days == 1 { return "A day ago" } else { return "\(Int(days)) days ago" } | |
} | |
if weeks < 4 { | |
if weeks == 1 { return "A week ago" } else { return "\(Int(weeks)) weeks ago" } | |
} | |
if months < 12 { | |
if months == 1 { "A month ago" } else { return "\(Int(months)) months ago" } | |
} | |
return "More than a year ago" | |
} | |
} | |
let date = Date(timeIntervalSince1970: 1488683746) | |
print (date) | |
print(date.quickRelativeTime()) | |
// 2017-03-05 03:15:46 +0000 | |
// A week ago |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment