Skip to content

Instantly share code, notes, and snippets.

@martinusso
Created August 25, 2020 16:32
Show Gist options
  • Save martinusso/89869de6f30522a047d2274b9cc89155 to your computer and use it in GitHub Desktop.
Save martinusso/89869de6f30522a047d2274b9cc89155 to your computer and use it in GitHub Desktop.
golang duration in days, months, years...
package main
import (
"fmt"
"math"
"time"
)
func RoundTime(input float64) int {
var result float64
if input < 0 {
result = math.Ceil(input - 0.5)
} else {
result = math.Floor(input + 0.5)
}
// only interested in integer, ignore fractional
i, _ := math.Modf(result)
return int(i)
}
func main() {
past, err := time.Parse("2006-01-02", "1984-09-11")
if err != nil {
panic(err)
}
diff := time.Since(past)
fmt.Println("Now : ", time.Now())
fmt.Println("Time reach the future date : ", past)
fmt.Println("Raw : ", diff)
fmt.Println("Hours : ", diff.Hours())
fmt.Println("Minutes : ", diff.Minutes())
fmt.Println("Seconds : ", diff.Seconds())
fmt.Println("Nano seconds : ", diff.Nanoseconds())
// get day, month and year
fmt.Println("Days : ", RoundTime(diff.Seconds()/86400))
fmt.Println("Weeks : ", RoundTime(diff.Seconds()/604800))
fmt.Println("Months : ", RoundTime(diff.Seconds()/2600640))
fmt.Println("Years : ", RoundTime(diff.Seconds()/31207680))
}
@KilianKae
Copy link

KilianKae commented Feb 1, 2022

Seems to me that number of months can be wrong, since each month has a different length (28/29/30/31) and you use a rounded duration.

Something like this should be exact.

func diffMonths(now time.Time, then time.Time) int {
	diffYears := now.Year() - then.Year()
	if diffYears == 0 {
		return int(now.Month() - then.Month())
	}

	if diffYears == 1 {
		return monthsTillEndOfYear(then) + int(now.Month())
	}

	yearsInMonths := (now.Year() - then.Year() - 1) * 12
	return yearsInMonths + monthsTillEndOfYear(then) + int(now.Month())
}

func monthsTillEndOfYear(then time.Time) int {
	return int(12 - then.Month())
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment