github.com/keybase/client/go@v0.0.0-20241007131713-f10651d043c8/kbtime/humanize.go (about)

     1  package kbtime
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  	"time"
     7  
     8  	humanize "github.com/dustin/go-humanize"
     9  )
    10  
    11  // RelTime is a thin wrapper around github.com/dustin/go-humanize
    12  // in order to provide more accurate data for large durations.
    13  // Below description is from go-humanize:
    14  //
    15  // RelTime formats a time into a relative string.
    16  //
    17  // It takes two times and two labels.  In addition to the generic time
    18  // delta string (e.g. 5 minutes), the labels are used applied so that
    19  // the label corresponding to the smaller time is applied.
    20  //
    21  // RelTime(timeInPast, timeInFuture, "earlier", "later") -> "3 weeks earlier"
    22  func RelTime(a, b time.Time, albl, blbl string) string {
    23  	lbl := albl
    24  	diff := b.Sub(a)
    25  	yearDiff := b.Year() - a.Year()
    26  	after := a.After(b)
    27  	if after {
    28  		lbl = blbl
    29  		diff = a.Sub(b)
    30  		yearDiff = a.Year() - b.Year()
    31  	}
    32  	if diff > 18*humanize.Month {
    33  		if lbl != "" {
    34  			lbl = " " + lbl
    35  		}
    36  		pl := ""
    37  		if yearDiff > 1 {
    38  			pl = "s"
    39  		}
    40  		return fmt.Sprintf("%d year%s%s", yearDiff, pl, lbl)
    41  	}
    42  
    43  	return strings.TrimSuffix(humanize.RelTime(a, b, albl, blbl), " ")
    44  }