From 8cf2f64d5e35dbc8ced383f88759e11d62052799 Mon Sep 17 00:00:00 2001 From: Alexander Medvednikov Date: Thu, 23 Apr 2026 20:48:46 +0300 Subject: [PATCH] time: fix time.Time is_zero method (fixes #24765) --- vlib/time/README.md | 2 ++ vlib/time/time.v | 7 +++++++ vlib/time/time_test.v | 12 ++++++++++++ 3 files changed, 21 insertions(+) diff --git a/vlib/time/README.md b/vlib/time/README.md index ceea9a258..39a5ea9ef 100644 --- a/vlib/time/README.md +++ b/vlib/time/README.md @@ -66,6 +66,8 @@ fn parse_rfc3339(s string) !Time `time.new(...)` validates the provided fields before calculating the Unix timestamp. Omitted `month` and `day` values default to `1`, and out-of-range values panic. +Use `t.is_zero()` to check whether a `time.Time` is still its zero value before formatting or +serializing it. Another very useful feature of the `time` module is the stop watch, for when you want to measure short time periods, elapsed while you diff --git a/vlib/time/time.v b/vlib/time/time.v index 8d10f13eb..15017d10a 100644 --- a/vlib/time/time.v +++ b/vlib/time/time.v @@ -152,6 +152,13 @@ pub fn (t Time) local_unix() i64 { return time_with_unix(t).unix } +// is_zero returns true when `t` is the zero value of `time.Time`. +@[inline] +pub fn (t Time) is_zero() bool { + return t.unix == 0 && t.year == 0 && t.month == 0 && t.day == 0 && t.hour == 0 && t.minute == 0 + && t.second == 0 && t.nanosecond == 0 && !t.is_local +} + // unix_milli returns the UNIX time with millisecond resolution. @[inline] pub fn (t Time) unix_milli() i64 { diff --git a/vlib/time/time_test.v b/vlib/time/time_test.v index 44f7e4abd..14004c32b 100644 --- a/vlib/time/time_test.v +++ b/vlib/time/time_test.v @@ -516,4 +516,16 @@ fn test_pre_epoch_unix_calculation() { day: 1 ).unix() == -62135596800 assert time.parse_rfc3339('0001-01-01T00:00:00Z')!.unix() == -62135596800 + assert t.is_zero() + // assert t.unix() == -62169984000 + assert t.custom_format('MMMM YYYY') == 'January 0' +} + +fn test_is_zero() { + assert time.Time{}.is_zero() + assert !time.unix(0).is_zero() + assert !time.new(year: 2024).is_zero() + assert !time.Time{ + is_local: true + }.is_zero() } -- 2.39.5