gitlab.com/postgres-ai/database-lab/v3@v3.0.3/pkg/util/time.go (about) 1 /* 2 2019 © Postgres.ai 3 */ 4 5 // Package util provides utility functions. Time and duration processing. 6 package util 7 8 import ( 9 "fmt" 10 "math" 11 "strconv" 12 "time" 13 14 "github.com/AlekSi/pointer" 15 ) 16 17 // TODO (akartasov): Check if functions are being used. 18 19 const ( 20 // NanosecondsInMillisecond defines a number of nanoseconds in an one millisecond. 21 NanosecondsInMillisecond = 1000000.0 22 // MillisecondsInSecond defines a number of milliseconds in an one second. 23 MillisecondsInSecond = 1000.0 24 25 // MillisecondsInMinute defines a number of milliseconds in an one minute. 26 MillisecondsInMinute = 60000.0 27 28 // DataStateAtFormat defines the format of a data state timestamp. 29 DataStateAtFormat = "20060102150405" 30 ) 31 32 // SecondsAgo returns a number of seconds elapsed from the current time. 33 func SecondsAgo(ts time.Time) uint { 34 now := time.Now() 35 36 seconds := now.Sub(ts).Seconds() 37 if seconds < 0 { 38 return 0 39 } 40 41 return uint(math.Floor(seconds)) 42 } 43 44 // DurationToString returns human-readable duration with dimensions. 45 func DurationToString(value time.Duration) string { 46 return MillisecondsToString(float64(value) / NanosecondsInMillisecond) 47 } 48 49 // MillisecondsToString return human-readable duration with dimensions. 50 func MillisecondsToString(value float64) string { 51 switch { 52 case value < MillisecondsInSecond: 53 return fmt.Sprintf("%.3f ms", value) 54 case value < MillisecondsInMinute: 55 return fmt.Sprintf("%.3f s", value/MillisecondsInSecond) 56 default: 57 return fmt.Sprintf("%.3f min", value/MillisecondsInMinute) 58 } 59 } 60 61 // FormatTime returns string representing time in UTC in defined format. 62 func FormatTime(t time.Time) string { 63 f := t.UTC() 64 return fmt.Sprintf("%d-%02d-%02d %02d:%02d:%02d UTC", f.Year(), f.Month(), 65 f.Day(), f.Hour(), f.Minute(), f.Second()) 66 } 67 68 // ParseUnixTime returns time parsed from unix timestamp integer. 69 func ParseUnixTime(str string) (time.Time, error) { 70 timeInt, err := strconv.ParseInt(str, 10, 64) 71 if err != nil { 72 return time.Time{}, err 73 } 74 75 return time.Unix(timeInt, 0), nil 76 } 77 78 // ParseCustomTime returns time parsed from string in defined format. 79 func ParseCustomTime(str string) (time.Time, error) { 80 return time.Parse(DataStateAtFormat, str) 81 } 82 83 // GetDataFreshness returns the time elapsed since the specified date. 84 func GetDataFreshness(dataStateAt string) *float64 { 85 parsedTime, err := ParseCustomTime(dataStateAt) 86 if err != nil { 87 return nil 88 } 89 90 return pointer.ToFloat64(time.Since(parsedTime).Seconds()) 91 }