In many applications, especially those involving user interactions, it's common to display timestamps as 'time ago' - a format that expresses the how long ago a certain date or time occurred, rather than displaying an exact timestamp. In Go, achieving this is straightforward, thanks to the concise standard library and community packages.
Table of Contents
Using the "time" package
The Go standard library includes a built-in package called time that provides robustness when dealing with dates and times. However, it does not directly support expressing times in the "time ago" format. To accomplish this, one often needs to compute the difference and format it manually. Here’s how you can do it:
package main
import (
"fmt"
"time"
)
func timeAgo(t time.Time) string {
duration := time.Since(t)
switch {
case duration.Hours() >= 24*365:
return fmt.Sprintf("%d years ago", int(duration.Hours())/24/365)
case duration.Hours() >= 24*30:
return fmt.Sprintf("%d months ago", int(duration.Hours())/24/30)
case duration.Hours() >= 24*7:
return fmt.Sprintf("%d weeks ago", int(duration.Hours())/24/7)
case duration.Hours() >= 24:
return fmt.Sprintf("%d days ago", int(duration.Hours())/24)
case duration.Hours() >= 1:
return fmt.Sprintf("%d hours ago", int(duration.Hours()))
case duration.Minutes() >= 1:
return fmt.Sprintf("%d minutes ago", int(duration.Minutes()))
default:
return "just now"
}
}
func main() {
pastTime := time.Date(2021, 10, 13, 0, 0, 0, 0, time.UTC)
fmt.Println(timeAgo(pastTime))
}
Using a third-party package
An easier approach is to use a third-party package designed to handle this with minimal effort. One popular package is github.com/dustin/go-humanize.
go get -u github.com/dustin/go-humanizeOnce you have the package, converting a timestamp to a "time ago" format is incredibly simple:
package main
import (
"fmt"
"time"
"github.com/dustin/go-humanize"
)
func main() {
// Specify the past time for demonstration
pastTime := time.Date(2021, 10, 13, 0, 0, 0, 0, time.UTC)
// Format time as "time ago"
fmt.Println(humanize.Time(pastTime))
}
Using go-humanize simplifies the need to manually calculate and format time distances. This makes code maintenance easier and more reliable, especially as package updates may introduce better calculations or additional features.
Conclusion
In this article, we examined two methods to convert a timestamp into a "time ago" format in Go: manually using the time package and using a third-party package. Both approaches have their own merits and can be selected based on project requirements, complexity, and personal preference.