Sling Academy
Home/Golang/How to convert datetime to time ago in Go

How to convert datetime to time ago in Go

Last updated: November 26, 2024

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.

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-humanize

Once 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.

Next Article: How to get the current timezone in Go

Previous Article: How to subtract 2 dates in Go

Series: Working with Date & Time in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant