import java.time.{Instant, Duration}
object RelativeTime {
def toRelativePastTime(past: Instant): String = {
val now = Instant.now()
val delta = Duration.between(past, now).abs()
val seconds = delta.getSeconds
val minutes = seconds / 60
val hours = seconds / 3600
val days = seconds / 86400
if (seconds < 60)
if (seconds == 1) "one second ago" else s"$seconds seconds ago"
else if (seconds < 3600)
if (minutes == 1) "a minute ago" else s"$minutes minutes ago"
else if (seconds < 86400)
if (hours == 1) "an hour ago" else s"$hours hours ago"
else if (seconds < 2592000) // 30 days
if (days == 1) "yesterday" else s"$days days ago"
else if (seconds < 31104000) { // 12 months
val months = days / 30
if (months <= 1) "a month ago" else s"$months months ago"
}
else {
val years = days / 365
if (years <= 1) "a year ago" else s"$years years ago"
}
}
def test(hoursAgo: Double): Unit = {
val secondsAgo = Math.round(hoursAgo * 3600).toLong
val past = Instant.now().minusSeconds(secondsAgo)
println(toRelativePastTime(past))
}
def main(args: Array[String]): Unit = {
test(0.01) // 36 seconds ago
test(0.2) // 12 minutes ago
test(3) // 3 hours ago
test(25) // yesterday
test(360) // 15 days ago
test(1239) // a month ago
test(2239) // 3 months ago
test(8760) // a year ago
test(98763) // 11 years ago
}
}
/*
run:
36 seconds ago
12 minutes ago
3 hours ago
yesterday
15 days ago
a month ago
3 months ago
a year ago
11 years ago
*/