Created
July 17, 2018 13:08
-
-
Save yoxisem544/1a2fbc045d4c13bd1b4d59884dfc5675 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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