Skip to content

Instantly share code, notes, and snippets.

@xremix
Created April 3, 2018 11:40
Show Gist options
  • Save xremix/5fc066a6be47912b0016eaf5ab38bc07 to your computer and use it in GitHub Desktop.
Save xremix/5fc066a6be47912b0016eaf5ab38bc07 to your computer and use it in GitHub Desktop.
Swift 3 human-readable Date Interval
class HumanTimeInterval{
// inspired by https://gist.github.com/skreutzberger/9122ac3683f3354a7e24
static func relativeDateInterval(date: Date) -> String? {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .abbreviated
formatter.includesApproximationPhrase = false
formatter.includesTimeRemainingPhrase = false
formatter.allowedUnits = [.year, .month, .weekOfMonth, .day, .hour, .minute, .second]
formatter.maximumUnitCount = 2
return formatter.string(from: date, to: Date())
}
}
//////////////
// Example
var date = Date(timeIntervalSince1970: 1522754818)
let str = HumanTimeInterval.relativeDateInterval(date: date)
print(str)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment