From 18cc20ff7bfe3e6492dd75018300a3fb1967918b Mon Sep 17 00:00:00 2001 From: Virgil Date: Wed, 1 Apr 2026 09:28:23 +0000 Subject: [PATCH] feat(i18n): add seconds granularity to TimeAgo Co-Authored-By: Virgil --- time.go | 8 +++++++- time_test.go | 5 +++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/time.go b/time.go index 06bda9d..8f18180 100644 --- a/time.go +++ b/time.go @@ -8,12 +8,18 @@ import ( // TimeAgo returns a localised relative time string. // +// TimeAgo(time.Now().Add(-4 * time.Second)) // "just now" // TimeAgo(time.Now().Add(-5 * time.Minute)) // "5 minutes ago" func TimeAgo(t time.Time) string { duration := time.Since(t) + if duration < 0 { + duration = 0 + } switch { - case duration < time.Minute: + case duration < 5*time.Second: return T("time.just_now") + case duration < time.Minute: + return FormatAgo(int(duration/time.Second), "second") case duration < time.Hour: return FormatAgo(int(duration.Minutes()), "minute") case duration < 24*time.Hour: diff --git a/time_test.go b/time_test.go index a0be0d1..37ce236 100644 --- a/time_test.go +++ b/time_test.go @@ -20,7 +20,8 @@ func TestTimeAgo_Good(t *testing.T) { duration time.Duration contains string }{ - {"just_now", 5 * time.Second, "just now"}, + {"just_now", 4 * time.Second, "just now"}, + {"seconds_ago", 5 * time.Second, "5 seconds ago"}, {"minutes_ago", 5 * time.Minute, "5 minutes ago"}, {"hours_ago", 3 * time.Hour, "3 hours ago"}, {"days_ago", 2 * 24 * time.Hour, "2 days ago"}, @@ -41,7 +42,7 @@ func TestTimeAgo_Good_EdgeCases(t *testing.T) { // Just under 1 minute got := TimeAgo(time.Now().Add(-59 * time.Second)) - assert.Contains(t, got, "just now") + assert.Contains(t, got, "seconds ago") // Exactly 1 minute got = TimeAgo(time.Now().Add(-60 * time.Second))