github.com/unicornultrafoundation/go-u2u@v1.0.0-rc1.0.20240205080301-e74a83d3fadc/utils/pretty_duration.go (about)

     1  package utils
     2  
     3  import (
     4  	"fmt"
     5  	"time"
     6  
     7  	"github.com/unicornultrafoundation/go-u2u/common"
     8  )
     9  
    10  // PrettyDuration is a combination of common.PrettyDuration and common.PrettyAge
    11  // It is a pretty printed version of a time.Duration value that rounds
    12  // the values up to a single most significant unit,
    13  // while showing the least significant part if duration isn't too large.
    14  type PrettyDuration time.Duration
    15  
    16  // ageUnits is a list of units the age pretty printing uses.
    17  var ageUnits = []struct {
    18  	Size   time.Duration
    19  	Symbol string
    20  }{
    21  	{12 * 30 * 24 * time.Hour, "y"},
    22  	{30 * 24 * time.Hour, "mo"},
    23  	{24 * time.Hour, "d"},
    24  	{time.Hour, "h"},
    25  	{time.Minute, "m"},
    26  }
    27  
    28  // String implements the Stringer interface, allowing pretty printing of duration
    29  // values rounded to the most significant time unit.
    30  func (t PrettyDuration) String() string {
    31  	// Calculate the time difference and handle the 0 cornercase
    32  	diff := time.Duration(t)
    33  	// Accumulate a precision of 3 components before returning
    34  	result, prec := "", 0
    35  	if diff < 0 {
    36  		diff = -diff
    37  		result = "-"
    38  	}
    39  
    40  	for _, unit := range ageUnits {
    41  		if diff > unit.Size {
    42  			result = fmt.Sprintf("%s%d%s", result, diff/unit.Size, unit.Symbol)
    43  			diff %= unit.Size
    44  
    45  			if prec += 1; prec >= 3 {
    46  				break
    47  			}
    48  		}
    49  	}
    50  	if prec < 3 {
    51  		return fmt.Sprintf("%s%s", result, common.PrettyDuration(diff).String())
    52  	}
    53  	return result
    54  }