Last active
February 11, 2019 13:01
-
-
Save vdeep/b0b48246b2afe7227cbf0668cbb399c4 to your computer and use it in GitHub Desktop.
Get time string 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
func timeStringFromDate(_ date: Date) -> String? { | |
let dateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date) | |
let dateTimestamp = date.timeIntervalSince1970 | |
let currentDateTimestamp = Date().timeIntervalSince1970 | |
let diff: TimeInterval = currentDateTimestamp - dateTimestamp | |
guard diff >= 0 else { | |
return nil | |
} | |
let yearTimeInterval: TimeInterval = 31536000 | |
let monthTimeInterval: TimeInterval = 2678400 | |
let dayTimeInterval: TimeInterval = 86400 | |
let hourTimeInterval: TimeInterval = 3600 | |
let minuteTimeInterval: TimeInterval = 60 | |
let secondTimeInterval: TimeInterval = 1 | |
if diff > yearTimeInterval { | |
let years = Int(diff / yearTimeInterval) | |
return "\(years) year\(years > 1 ? "s" : "") ago" | |
} | |
if diff > monthTimeInterval { | |
let months = Int(diff / monthTimeInterval) | |
return "\(months) month\(months > 1 ? "s" : "") ago" | |
} | |
if diff > dayTimeInterval { | |
let days = Int(diff / dayTimeInterval) | |
return "\(days) day\(days > 1 ? "s" : "") ago" | |
} | |
if diff > hourTimeInterval { | |
let hours = Int(diff / hourTimeInterval) | |
return "\(hours) hour\(hours > 1 ? "s" : "") ago" | |
} | |
if diff > minuteTimeInterval { | |
let minutes = Int(diff / minuteTimeInterval) | |
return "\(minutes) minute\(minutes > 1 ? "s" : "") ago" | |
} | |
if diff > secondTimeInterval { | |
let seconds = Int(diff) | |
return "\(seconds) second\(seconds > 1 ? "s" : "") ago" | |
} | |
return "just now" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment