diff --git a/timex/doc.go b/timex/doc.go new file mode 100644 index 0000000..477c1dd --- /dev/null +++ b/timex/doc.go @@ -0,0 +1,4 @@ +/* +Package timex provides some handy [time]-related functions. +*/ +package timex diff --git a/timex/funcs.go b/timex/funcs.go new file mode 100644 index 0000000..5003c83 --- /dev/null +++ b/timex/funcs.go @@ -0,0 +1,35 @@ +package timex + +import ( + `time` +) + +/* +F64Seconds returns [time.Time] `t` as a 64-bit float of . +(where is the number of nanoseconds since , +and is the number of seconds since the UNIX epoch). + +This can be used to represent a UNIX Epoch timestamp as seconds but with nanosecond precision. +*/ +func F64Seconds(t time.Time) (f64 float64) { + return F64Nanoseconds(t) / float64(time.Second) +} + +/* +F64Milliseconds is like [F64Seconds] but with a millisecond integer. +*/ +func F64Milliseconds(t time.Time) (f64 float64) { + return F64Nanoseconds(t) / float64(time.Millisecond) +} + +/* +F64Microseconds is like [F64Seconds] but with a microsecond integer. +*/ +func F64Microseconds(t time.Time) (f64 float64) { + return F64Nanoseconds(t) / float64(time.Microsecond) +} + +// F64Nanoseconds returns [time.Time.UnixNano] as a float64. +func F64Nanoseconds(t time.Time) (f64 float64) { + return float64(t.UnixNano()) +} diff --git a/timex/funcs_test.go b/timex/funcs_test.go new file mode 100644 index 0000000..1529f62 --- /dev/null +++ b/timex/funcs_test.go @@ -0,0 +1,30 @@ +package timex + +import ( + "testing" + `time` +) + +func TestF64(t *testing.T) { + + var tmNano float64 = 1766533329999999999 + var tmSeconds float64 = 1766533329.999999999 + var tmMilli float64 = 1766533329999.999999 + var tmMicro float64 = 1766533329999999.999 + // 2025-12-23 23:42:09.999999999 +0000 UTC + var tm time.Time = time.Unix(1766533329, int64(time.Second-1)) + + if F64Seconds(tm) != tmSeconds { + t.Fatalf("Failed seconds: %f != %f", F64Seconds(tm), tmSeconds) + } + if F64Milliseconds(tm) != tmMilli { + t.Fatalf("Failed milliseconds: %f != %f", F64Milliseconds(tm), tmMilli) + } + if F64Microseconds(tm) != tmMicro { + t.Fatalf("Failed microseconds: %f != %f", F64Microseconds(tm), tmMicro) + } + if F64Nanoseconds(tm) != tmNano { + t.Fatalf("Failed nanoseconds: %f != %f", F64Nanoseconds(tm), tmNano) + } + +}