Created
April 26, 2012 18:11
-
-
Save Shadowfiend/2501570 to your computer and use it in GitHub Desktop.
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
// Helpers for distances in words. | |
class TimeDeltaHelpers(timeDelta:Long) { | |
// Turns the time delta (in milliseconds) into a word distance, e.g. `5 | |
// days ago' or `3 hours ago'. | |
def distanceInWords : String = { | |
fuzzyTimeFromDelta(timeDelta) | |
} | |
private val second = 1 | |
private val minute = 60 * second | |
private val hour = 60 * minute | |
private val day = 24 * hour | |
private val month = 30 * day | |
private val year = 365 * day | |
private def fuzzyTimeFromDelta(delta:Long) : String = { | |
def floor(value:Double) = { | |
math.floor(value).longValue | |
} | |
val realDelta = floor(delta / 1000.0).longValue | |
if (realDelta < 1 * minute) | |
(realDelta <= 1) ? "one second ago" | realDelta + " seconds ago" | |
else if (realDelta < 2 * minute) | |
"a minute ago" | |
else if (realDelta < 45 * minute) | |
floor(realDelta / minute) + " minutes ago" | |
else if (realDelta < 90 * minute) | |
"an hour ago" | |
else if (realDelta < 24 * hour) | |
floor(realDelta / hour) + " hours ago" | |
else if (realDelta < 48 * hour) | |
"yesterday" | |
else if (realDelta < 30 * day) | |
floor(realDelta / day) + " days ago" | |
else if (realDelta < 12 * month) { | |
val months = floor(realDelta / month) | |
(months <= 1) ? "one month ago" | months + " months ago" | |
} else { | |
val years = floor(realDelta / year) | |
(years <= 1) ? "one year ago" | years + " years ago" | |
} | |
} | |
} | |
// Helpers for distances in words with respect to other times. | |
class RelativeTimeHelpers(date:Date) { | |
// Returns the distance, in words, from the current time. | |
def distanceInWords : String = { | |
((new Date).getTime - date.getTime).distanceInWords | |
} | |
// Returns the distance, in words, from the given other date. | |
def distanceInWordsTo(otherDate:Date) : String = { | |
(otherDate.getTime - date.getTime).distanceInWords | |
} | |
} | |
implicit def long2timeDeltaHelpers(value:Long) : TimeDeltaHelpers = { | |
new TimeDeltaHelpers(value) | |
} | |
implicit def date2relativeTimeHelpers(value:Date) : RelativeTimeHelpers = { | |
new RelativeTimeHelpers(value) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment