Skip to content

Commit

Permalink
Time now handles long ago and a while from now
Browse files Browse the repository at this point in the history
  • Loading branch information
mholt authored and dustin committed Apr 22, 2014
1 parent b925560 commit 4539fc6
Showing 1 changed file with 20 additions and 9 deletions.
29 changes: 20 additions & 9 deletions times.go
Expand Up @@ -7,12 +7,13 @@ import (

// Seconds-based time units
const (
Minute = 60
Hour = 60 * Minute
Day = 24 * Hour
Week = 7 * Day
Month = 30 * Day
Year = 12 * Month
Minute = 60
Hour = 60 * Minute
Day = 24 * Hour
Week = 7 * Day
Month = 30 * Day
Year = 12 * Month
LongTime = 37 * Year
)

// Time formats a time into a relative string.
Expand All @@ -22,13 +23,14 @@ func Time(then time.Time) string {

lbl := "ago"
diff := now.Unix() - then.Unix()
if then.After(now) {

after := then.After(now)
if after {
lbl = "from now"
diff = then.Unix() - now.Unix()
}

switch {

case diff <= 0:
return "now"
case diff <= 2:
Expand Down Expand Up @@ -63,6 +65,15 @@ func Time(then time.Time) string {

case diff < 18*Month:
return fmt.Sprintf("1 year %s", lbl)
case diff < 2*Year:
return fmt.Sprintf("2 years %s", lbl)
case diff < LongTime:
return fmt.Sprintf("%d years %s", diff/Year, lbl)
}

if after {
return "a while from now"
} else {
return "long ago"
}
return then.String()
}

0 comments on commit 4539fc6

Please sign in to comment.