github.com/haraldrudell/parl@v0.4.176/ptime/epoch.go (about) 1 /* 2 © 2023–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/) 3 ISC License 4 */ 5 6 package ptime 7 8 import "time" 9 10 var ptimeEpoch = time.Now() 11 12 // Epoch translates a time value to a 64-bit value that can be used atomically. 13 type Epoch time.Duration 14 15 // EpochNow translates a time value to a 64-bit value that can be used atomically. 16 func EpochNow(t ...time.Time) (epoch Epoch) { 17 var t0 time.Time 18 if len(t) > 0 { 19 t0 = t[0] 20 } else { 21 t0 = time.Now() 22 } 23 if t0.IsZero() { 24 return // zero value: epoch 0 25 } 26 return Epoch(t0.Sub(ptimeEpoch)) 27 } 28 29 // Time returns the time.Time value corresponding to epoch 30 func (epoch Epoch) Time() (t time.Time) { 31 if epoch == 0 { 32 return // epoch zero means time.Time{} ie. time.IsZero() 33 } 34 return ptimeEpoch.Add(time.Duration(epoch)) 35 } 36 37 // IsValid returns true if epoch is not zero-time, ie. Epoch(0) corredsponding to time.TIME{} and Time.IsZero 38 func (epoch Epoch) IsValid() (isValid bool) { 39 return epoch != 0 40 }