From 153b7f00df38ffc44198a83f71279061ad5ebe26 Mon Sep 17 00:00:00 2001 From: Delyan Angelov Date: Thu, 28 Nov 2024 12:47:05 +0200 Subject: [PATCH] time: add module helpers unix_milli/1, unix_micro/1, unix_nano/1 and tests for them (#22997) --- vlib/time/unix.v | 41 +++++++++++++++++++++++------------------ vlib/time/unix_test.v | 12 ++++++++++++ 2 files changed, 35 insertions(+), 18 deletions(-) create mode 100644 vlib/time/unix_test.v diff --git a/vlib/time/unix.v b/vlib/time/unix.v index 0fa4b24ee..f91fcf982 100644 --- a/vlib/time/unix.v +++ b/vlib/time/unix.v @@ -3,25 +3,30 @@ // that can be found in the LICENSE file. module time -// unix returns a Time struct calculated from a Unix timestamp (number of seconds since 1970-01-01) +// unix returns a Time calculated from the given Unix timestamp in seconds since 1970-01-01 pub fn unix(epoch i64) Time { - // Split into day and time - mut day_offset := epoch / seconds_per_day - if epoch % seconds_per_day < 0 { - // Compensate for round towards zero on integers as we want floored instead - day_offset-- - } - year, month, day := calculate_date_from_day_offset(day_offset) - hr, min, sec := calculate_time_from_second_offset(epoch % seconds_per_day) - return Time{ - year: year - month: month - day: day - hour: hr - minute: min - second: sec - unix: epoch - } + return unix_nanosecond(epoch, 0) +} + +// unix_milli returns a Time calculated from the given Unix timestamp in milliseconds since 1970-01-01 +pub fn unix_milli(ms i64) Time { + return ts_to_time_impl(ms, 1_000, 1_000_000) +} + +// unix_micro returns a Time calculated from the given Unix timestamp in microseconds since 1970-01-01 +pub fn unix_micro(us i64) Time { + return ts_to_time_impl(us, 1_000_000, 1_000) +} + +// unix_nano returns a Time calculated from the given Unix timestamp in nanoseconds since 1970-01-01 +pub fn unix_nano(ns i64) Time { + return ts_to_time_impl(ns, 1_000_000_000, 1) +} + +fn ts_to_time_impl(value i64, down i64, up i64) Time { + epoch := value / down + remainder := (value % down) * up + return unix_nanosecond(epoch, int(remainder)) } // unix_microsecond returns a Time struct, given an Unix timestamp in seconds, and a microsecond value diff --git a/vlib/time/unix_test.v b/vlib/time/unix_test.v new file mode 100644 index 000000000..8a99af90a --- /dev/null +++ b/vlib/time/unix_test.v @@ -0,0 +1,12 @@ +import time + +fn test_unix_timestamp_conversion_to_time() { + t := time.now() + ss := dump(time.unix(t.unix())) + sms := dump(time.unix_milli(t.unix_milli())) + sus := dump(time.unix_micro(t.unix_micro())) + sns := dump(time.unix_nano(t.unix_nano())) + assert sns.format_ss() == ss.format_ss() + assert sns.format_ss_milli() == sms.format_ss_milli() + assert sns.format_ss_micro() == sus.format_ss_micro() +} -- 2.39.5