prime8dev

prime8dev
git clone https://git.prime8.dev/prime8dev.git
Log | Files | Refs | README | LICENSE

uptime.go (650B)


      1 package utils
      2 
      3 import (
      4 	"fmt"
      5 	"time"
      6 )
      7 
      8 // Uptime renders time since birth in uptime(1) style, e.g. "18y 183d".
      9 func Uptime(birth, now time.Time) string {
     10 	// count calendar days on the birth date's clock, not the server's
     11 	now = now.In(birth.Location())
     12 	if now.Before(birth) {
     13 		return "0d"
     14 	}
     15 	years := now.Year() - birth.Year()
     16 	anniv := birth.AddDate(years, 0, 0)
     17 	if anniv.After(now) {
     18 		years--
     19 		anniv = birth.AddDate(years, 0, 0)
     20 	}
     21 	y, m, d := now.Date()
     22 	today := time.Date(y, m, d, 0, 0, 0, 0, birth.Location())
     23 	days := 0
     24 	for anniv.AddDate(0, 0, days+1).Compare(today) <= 0 {
     25 		days++
     26 	}
     27 	return fmt.Sprintf("%dy %dd", years, days)
     28 }