How to calculate relative past time from a given date & time (e.g., 3 hours ago, 5 days ago, a month ago) in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "math"
    "time"
)

func ToRelativePastTime(past time.Time) string {
    now := time.Now().UTC()
    delta := math.Abs(now.Sub(past).Seconds())

    seconds := int(delta)
    minutes := seconds / 60
    hours := seconds / 3600
    days := seconds / 86400

    if seconds < 60 {
        if seconds == 1 {
            return "one second ago"
        }
        return fmt.Sprintf("%d seconds ago", seconds)
    }

    if seconds < 3600 {
        if minutes == 1 {
            return "a minute ago"
        }
        return fmt.Sprintf("%d minutes ago", minutes)
    }

    if seconds < 86400 {
        if hours == 1 {
            return "an hour ago"
        }
        return fmt.Sprintf("%d hours ago", hours)
    }

    if seconds < 2592000 { // 30 days
        if days == 1 {
            return "yesterday"
        }
        return fmt.Sprintf("%d days ago", days)
    }

    if seconds < 31104000 { // 12 months
        months := days / 30
        if months <= 1 {
            return "a month ago"
        }
        return fmt.Sprintf("%d months ago", months)
    }

    years := days / 365
    if years <= 1 {
        return "a year ago"
    }
    return fmt.Sprintf("%d years ago", years)
}

func test(hoursAgo float64) {
    secondsAgo := int(hoursAgo * 3600)
    past := time.Now().UTC().Add(-time.Duration(secondsAgo) * time.Second)
    fmt.Println(ToRelativePastTime(past))
}

func main() {
    test(0.01)   // 36 seconds ago
    test(0.2)    // 12 minutes ago
    test(3)      // 3 hours ago
    test(25)     // yesterday
    test(360)    // 15 days ago
    test(1239)   // a month ago
    test(2239)   // 3 months ago
    test(8760)   // a year ago
    test(98763)  // 11 years ago
}



/*
run:

36 seconds ago
12 minutes ago
3 hours ago
yesterday
15 days ago
a month ago
3 months ago
a year ago
11 years ago

*/

 



answered Apr 13 by avibootz

Related questions

...