Skip to content

Instantly share code, notes, and snippets.

@skreutzberger
Last active April 17, 2023 12:32
Show Gist options
  • Save skreutzberger/9122ac3683f3354a7e24 to your computer and use it in GitHub Desktop.
Save skreutzberger/9122ac3683f3354a7e24 to your computer and use it in GitHub Desktop.
Swift 2 function for human-readable time interval
/// returns optional relative date interval string like "2d"
/// depending on the unitsstyle, see docs at http://apple.co/1ox2sOX
/// inject an existing NSDateComponentsFormatter() for performance
func relativeDateInterval(date: NSDate,
unitsStyle: NSDateComponentsFormatterUnitsStyle,
formatter: NSDateComponentsFormatter) -> String? {
// inspired by top answer at http://bit.ly/1TzMQqV
let formatter = NSDateComponentsFormatter()
formatter.unitsStyle = unitsStyle //.Abbreviated, .Full, ...
formatter.includesApproximationPhrase = false
formatter.includesTimeRemainingPhrase = false
formatter.allowedUnits = [.Year, .Month, .WeekOfMonth, .Day, .Hour, .Minute, .Second]
formatter.maximumUnitCount = 1
return formatter.stringFromDate(date, toDate: NSDate())
}
//////////////
// Use example
let formatter = NSDateComponentsFormatter()
let date = NSDate() // change that to a date in the past or it will display "0s"
let str = relativeDateInterval(date, unitsStyle: .Abbreviated, formatter: formatter)
print(str)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment