Skip to content

Instantly share code, notes, and snippets.

@yoxisem544
Created July 17, 2018 13:08
Show Gist options
  • Save yoxisem544/1a2fbc045d4c13bd1b4d59884dfc5675 to your computer and use it in GitHub Desktop.
Save yoxisem544/1a2fbc045d4c13bd1b4d59884dfc5675 to your computer and use it in GitHub Desktop.
extension Date {
var secondPassedFromNow: TimeInterval {
return -timeIntervalSince(Date())
}
var relativeDate: String {
// if second is negative, means its in future
let seconds = secondPassedFromNow.rounded(.down)
guard seconds >= 0 else { return "\(seconds)" }
switch seconds {
case 0..<60:
return "\(Int(seconds))秒前"
case 60..<3600:
return "\(Int(seconds/60))分鐘前"
case 3600..<86400:
return "\(Int(seconds/3600))小時前"
case 86400..<604800:
return "\(Int(seconds/86400))天前"
default:
let formatter = DateFormatter()
formatter.dateFormat = "MMM d yyyy"
return formatter.string(from: self)
}
}
}
Date(timeInterval: -53.23, since: Date()).relativeDate // "53秒前"
Date(timeInterval: -2123.213213, since: Date()).relativeDate // "35分鐘前"
Date(timeInterval: -7300.2, since: Date()).relativeDate // "2小時前"
Date(timeInterval: -186400, since: Date()).relativeDate // "2天前"
Date(timeInterval: -2222253.23, since: Date()).relativeDate // "Jun 22 2018"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment