From 7c8641771f5f3a705bd5c1c3f42cf6470046b4f8 Mon Sep 17 00:00:00 2001 From: "Tom D." <15268361+anastygnome@users.noreply.github.com> Date: Thu, 12 Nov 2026 12:31:20 +0100 Subject: [PATCH 1/2] fix(offset): match GNU timezone behavior --- src/items/builder.rs | 159 ++++++++++++++++++++++++++++++++++++------- src/items/offset.rs | 140 ++++++++++++++++++++++++++----------- 2 files changed, 234 insertions(+), 65 deletions(-) diff --git a/src/items/builder.rs b/src/items/builder.rs index 4fd6aca2..b747b5c1 100644 --- a/src/items/builder.rs +++ b/src/items/builder.rs @@ -284,6 +284,8 @@ impl DateTimeBuilder { } else { base }; + let mut named_fixed_zone_applied = false; + let mut named_fixed_hour_adjustment = 0; // 4a. Apply date. if let Some(date) = self.date { @@ -304,7 +306,38 @@ impl DateTimeBuilder { } let t: civil::Time = time.try_into()?; + let local = civil::DateTime::new( + dt.year(), + dt.month(), + dt.day(), + t.hour(), + t.minute(), + t.second(), + t.subsec_nanosecond(), + )?; + let named_zone_is_local = self + .offset + .as_ref() + .and_then(|offset| offset.name()) + .is_some_and(|name| matching_local_zone_at(&dt, local, name).is_some()); + if !named_zone_is_local + && self + .offset + .as_ref() + .and_then(|offset| offset.name()) + .is_some() + { + if let Some(offset) = self.offset.as_ref() { + let (offset, hour_adjustment) = offset.clone().normalize(); + dt = dt.datetime().to_zoned_datetime((&offset).try_into()?)?; + named_fixed_hour_adjustment = hour_adjustment; + named_fixed_zone_applied = true; + } + } dt = dt.with().time(t).build()?; + if named_fixed_hour_adjustment != 0 { + dt = dt.checked_add(Span::new().hours(i64::from(named_fixed_hour_adjustment)))?; + } } // 4c. Apply weekday. @@ -349,35 +382,74 @@ impl DateTimeBuilder { dt = dt.checked_add(Span::new().try_days(delta)?)?; } - // 4d. Apply fixed offset. This anchors the instant before relative - // adjustments so that "1970/01/01 UTC N seconds" adds N seconds to the - // fixed-offset instant rather than to a local wall-clock that may drift - // across a DST boundary (see issue uutils/coreutils#12555). - if let Some(offset) = self.offset { - let (offset, hour_adjustment) = offset.normalize(); - dt = dt.checked_add(Span::new().hours(hour_adjustment))?; - dt = dt.datetime().to_zoned_datetime((&offset).try_into()?)?; + // 4d. Apply the named or fixed offset. A named abbreviation can + // describe the active local timezone rather than a fixed offset. + // Preserve that zone when the abbreviation matches the requested wall + // clock so daylight-saving transitions are resolved using the base + // zone's rules. + let named_local_zone = self + .offset + .as_ref() + .and_then(|offset| offset.name()) + .and_then(|name| matching_local_zone(&dt, name)); + let use_named_local_zone = named_local_zone.is_some(); + if use_named_local_zone { + if let Some(offset) = self.offset.as_ref() { + let (offset, hour_adjustment) = offset.clone().normalize(); + dt = dt.checked_add(Span::new().hours(i64::from(hour_adjustment)))?; + dt = dt.datetime().to_zoned_datetime((&offset).try_into()?)?; + } + } + + // Apply a fixed offset before relative adjustments. For offsets larger + // than 24 hours, first reinterpret the wall clock in the normalized + // zone and then apply the remaining hour correction. + if !use_named_local_zone && !named_fixed_zone_applied { + if let Some(offset) = self.offset { + let (offset, hour_adjustment) = offset.normalize(); + dt = dt.datetime().to_zoned_datetime((&offset).try_into()?)?; + dt = dt.checked_add(Span::new().hours(i64::from(hour_adjustment)))?; + } } // 4e. Apply relative adjustments. - for rel in self.relative { - dt = match rel { - relative::Relative::Years(_) | relative::Relative::Months(_) => { - // GNU way of calculating relative months and years. - // GNU changes the month/year and then checks if the target month has - // this day. If this day does not exist in the target month it overflows - // the difference. - let original_day_of_month = dt.day(); - dt = dt.checked_add::(rel.try_into()?)?; - if original_day_of_month != dt.day() { - dt = dt.checked_add( - (original_day_of_month.checked_sub(dt.day()).unwrap_or(0)).days(), - )?; - } - dt + if let Some(zone) = named_local_zone { + let mut date_relative = Vec::new(); + let mut time_relative = Vec::new(); + for rel in self.relative { + match rel { + relative::Relative::Years(_) + | relative::Relative::Months(_) + | relative::Relative::Days(_) => date_relative.push(rel), + _ => time_relative.push(rel), } - _ => dt.checked_add::(rel.try_into()?)?, - }; + } + + for rel in date_relative { + dt = dt.checked_add::(rel.try_into()?)?; + } + dt = dt.with_time_zone(zone); + for rel in time_relative { + dt = dt.checked_add::(rel.try_into()?)?; + } + } else { + // Apply relative adjustments in their existing order. Calendar + // month/year grouping is handled by the separate relative-fix PR. + for rel in self.relative { + dt = match rel { + relative::Relative::Years(_) | relative::Relative::Months(_) => { + let original_day_of_month = dt.day(); + dt = dt.checked_add::(rel.try_into()?)?; + if original_day_of_month != dt.day() { + dt = dt.checked_add( + (original_day_of_month.checked_sub(dt.day()).unwrap_or(0)).days(), + )?; + } + dt + } + _ => dt.checked_add::(rel.try_into()?)?, + }; + } } Ok(dt) @@ -552,6 +624,43 @@ fn weekday_monday0(day: weekday::Day) -> u8 { } } +fn matching_local_zone(dt: &ZonedDateTime, name: &str) -> Option { + matching_local_zone_at(dt, dt.datetime(), name) +} + +fn matching_local_zone_at( + dt: &ZonedDateTime, + local: civil::DateTime, + name: &str, +) -> Option { + // GNU's universal abbreviations always denote fixed UTC, even if the + // active local zone happens to use the same abbreviation. + if matches!(name, "utc" | "ut" | "gmt" | "z") { + return None; + } + + let zone = dt.time_zone(); + zone.iana_name()?; + let ambiguous = zone.to_ambiguous_zoned_datetime(local); + for candidate in [ + ambiguous.clone().compatible(), + ambiguous.clone().earlier(), + ambiguous.later(), + ] + .into_iter() + .flatten() + { + if candidate + .strftime("%Z") + .to_string() + .eq_ignore_ascii_case(name) + { + return Some(zone.clone()); + } + } + None +} + impl TryFrom> for DateTimeBuilder { type Error = &'static str; diff --git a/src/items/offset.rs b/src/items/offset.rs index a4f3342a..a6065988 100644 --- a/src/items/offset.rs +++ b/src/items/offset.rs @@ -36,7 +36,7 @@ use winnow::{ }; use super::{ - primitive::{colon, ctx_err, dec_uint, dec_uint_str, plus_or_minus, s}, + primitive::{colon, ctx_err, dec_uint_str, plus_or_minus, s}, relative, }; @@ -48,8 +48,9 @@ use super::{ #[derive(PartialEq, Debug, Clone, Default)] pub(super) struct Offset { negative: bool, - hours: u8, - minutes: u8, + hours: u16, + minutes: u16, + name: Option, } impl Offset { @@ -70,18 +71,19 @@ impl Offset { } } let (total_minutes, negative) = combine( - (self.hours as u16) * 60 + (self.minutes as u16), + self.hours * 60 + self.minutes, self.negative, - (offset.hours as u16) * 60 + (offset.minutes as u16), + offset.hours * 60 + offset.minutes, offset.negative, ); - let hours = (total_minutes / 60) as u8; - let minutes = (total_minutes % 60) as u8; + let hours = total_minutes / 60; + let minutes = total_minutes % 60; Offset { negative, hours, minutes, + name: self.name.or(offset.name), } } @@ -93,17 +95,18 @@ impl Offset { /// - Otherwise, the hour field is reduced to 23 while preserving the minute /// field, and the function returns the normalized offset along with the /// hour adjustment needed to reach the original offset. - pub(super) fn normalize(self) -> (Offset, i8) { + pub(super) fn normalize(self) -> (Offset, i32) { if self.hours < 24 || (self.hours == 24 && self.minutes == 0) { return (self, 0); } - let hour_adjustment = (self.hours as i8 - 23) * if self.negative { 1 } else { -1 }; + let hour_adjustment = (self.hours as i32 - 23) * if self.negative { 1 } else { -1 }; ( Offset { negative: self.negative, hours: 23, minutes: self.minutes, + name: self.name, }, hour_adjustment, ) @@ -117,23 +120,38 @@ impl Offset { secs } } + + pub(super) fn name(&self) -> Option<&str> { + self.name.as_deref() + } } impl TryFrom<(bool, u8, u8)> for Offset { type Error = &'static str; fn try_from((negative, hours, minutes): (bool, u8, u8)) -> Result { - if hours > 24 { - return Err("timezone hour must be between 0 and 24"); - } - if minutes > 60 || (hours == 24 && minutes != 0) { - return Err("timezone minute must be between 0 and 60"); + Self::from_parts(negative, u32::from(hours), u32::from(minutes)) + } +} + +impl Offset { + /// Construct an offset from raw hour and minute fields. GNU normalizes + /// excess minutes into hours, but rejects offsets whose total magnitude + /// exceeds 24 hours. + fn from_parts(negative: bool, hours: u32, minutes: u32) -> Result { + let total_minutes = hours + .checked_mul(60) + .and_then(|hours| hours.checked_add(minutes)) + .ok_or("timezone offset is too large")?; + if total_minutes > 24 * 60 { + return Err("timezone offset must be between -24:00 and +24:00"); } - Ok(Offset { + Ok(Self { negative, - hours, - minutes, + hours: (total_minutes / 60) as u16, + minutes: (total_minutes % 60) as u16, + name: None, }) } } @@ -146,6 +164,7 @@ impl TryFrom<&Offset> for jiff::tz::TimeZone { negative, hours, minutes, + .. }: &Offset, ) -> Result { let secs = (*hours as i32) * 3600 + (*minutes as i32) * 60; @@ -247,6 +266,7 @@ fn timezone_name_offset(input: &mut &str) -> ModalResult { negative: false, hours: 1, minutes: 0, + name: None, })); } input.reset(&start); @@ -266,12 +286,16 @@ fn timezone_name_offset(input: &mut &str) -> ModalResult { /// Parse a timezone offset with a colon separating hours and minutes, e.g., /// `+08:00`, `+8:00`, `+8:0`. fn timezone_offset_colon(input: &mut &str) -> ModalResult { - (plus_or_minus, s(dec_uint), s(colon), s(dec_uint)) + (plus_or_minus, s(dec_uint_str), s(colon), s(dec_uint_str)) .parse_next(input) .and_then(|(sign, hours, _, minutes)| { - (sign == '-', hours, minutes) - .try_into() - .map_err(|e| ErrMode::Cut(ctx_err(e))) + let hours = hours + .parse::() + .map_err(|_| ErrMode::Cut(ctx_err("timezone hour is too large")))?; + let minutes = minutes + .parse::() + .map_err(|_| ErrMode::Cut(ctx_err("timezone minute is too large")))?; + Offset::from_parts(sign == '-', hours, minutes).map_err(|e| ErrMode::Cut(ctx_err(e))) }) } @@ -304,15 +328,13 @@ fn timezone_offset_colonless(input: &mut &str) -> ModalResult { _ => return None, }; - let hours = h_str.parse::().ok()?; - let minutes = m_str.parse::().ok()?; - Some((sign, hours, minutes)) + let hours = h_str.parse::().ok()?; + let minutes = m_str.parse::().ok()?; + Some((sign == '-', hours, minutes)) }) .parse_next(input) - .and_then(|(sign, hours, minutes)| { - (sign == '-', hours, minutes) - .try_into() - .map_err(|e| ErrMode::Cut(ctx_err(e))) + .and_then(|(negative, hours, minutes)| { + Offset::from_parts(negative, hours, minutes).map_err(|e| ErrMode::Cut(ctx_err(e))) }) } @@ -401,14 +423,21 @@ fn timezone_name_to_offset(input: &str) -> ModalResult<(Offset, bool)> { "akdt" => (true, 8, 0, false), "adt" => (true, 3, 0, false), "a" => (false, 1, 0, true), + // Australian abbreviations accepted by GNU date. + "aest" => (false, 10, 0, true), + "aedt" => (false, 11, 0, false), + "acst" => (false, 9, 30, true), + "acdt" => (false, 10, 30, false), + "awst" => (false, 8, 0, false), _ => return Err(ErrMode::Backtrack(ContextError::new())), }; Ok(( Offset { negative, - hours, - minutes, + hours: hours as u16, + minutes: minutes as u16, + name: Some(input.to_owned()), }, takes_dst, )) @@ -421,11 +450,17 @@ mod tests { fn off(negative: bool, hours: u8, minutes: u8) -> Offset { Offset { negative, - hours, - minutes, + hours: u16::from(hours), + minutes: u16::from(minutes), + name: None, } } + fn unnamed(mut offset: Offset) -> Offset { + offset.name = None; + offset + } + #[test] fn timezone_offset_with_colon() { for (input, expected) in [ @@ -448,9 +483,11 @@ mod tests { } for input in [ - "+25:00", // invalid: hours > 24 - "-23:61", // invalid: minutes > 60 - "+24:01", // invalid: minutes > 0 when hours == 24 + "+25:00", // invalid: hours > 24 + "-23:61", // invalid: minutes > 60 + "+24:01", // invalid: minutes > 0 when hours == 24 + "+999999999999999999999:00", // invalid: hour does not fit u32 + "+01:999999999999999999999", // invalid: minute does not fit u32 ] { let mut s = input; assert!(timezone_offset(&mut s).is_err(), "{input}"); @@ -511,10 +548,19 @@ mod tests { ("bst", off(false, 1, 0)), // British Summer, was +6 ("gst", off(false, 10, 0)), // Guam Standard, was +4 ("sst", off(true, 12, 0)), // was -11 + ("aest", off(false, 10, 0)), + ("aedt", off(false, 11, 0)), + ("acst", off(false, 9, 30)), + ("acdt", off(false, 10, 30)), + ("awst", off(false, 8, 0)), ("z123", off(false, 0, 0)), // space separator can be ignored if immediately followed by digits (GNU date behavior) ] { let mut s = input; - assert_eq!(timezone_name_offset(&mut s).unwrap(), expected, "{input}"); + assert_eq!( + unnamed(timezone_name_offset(&mut s).unwrap()), + expected, + "{input}" + ); } for input in [ @@ -541,7 +587,11 @@ mod tests { ("y-24", off(true, 36, 0)), // maximum possible negative offset (y=-12) ] { let mut s = input; - assert_eq!(timezone_name_offset(&mut s).unwrap(), expected, "{input}"); + assert_eq!( + unnamed(timezone_name_offset(&mut s).unwrap()), + expected, + "{input}" + ); } for input in [ @@ -567,7 +617,11 @@ mod tests { ("a dst", off(false, 2, 0)), // military letter (a=+1) ] { let mut s = input; - assert_eq!(timezone_name_offset(&mut s).unwrap(), expected, "{input}"); + assert_eq!( + unnamed(timezone_name_offset(&mut s).unwrap()), + expected, + "{input}" + ); assert!(s.is_empty(), "{input}"); } @@ -594,12 +648,18 @@ mod tests { // "utc +8 years" is "utc" followed by the relative item "+8 years". let mut s = "utc +8 years"; - assert_eq!(timezone_name_offset(&mut s).unwrap(), off(false, 0, 0)); + assert_eq!( + unnamed(timezone_name_offset(&mut s).unwrap()), + off(false, 0, 0) + ); assert_eq!(s, " +8 years"); // Without a relative item, the offset is still merged. let mut s = "utc +8"; - assert_eq!(timezone_name_offset(&mut s).unwrap(), off(false, 8, 0)); + assert_eq!( + unnamed(timezone_name_offset(&mut s).unwrap()), + off(false, 8, 0) + ); assert!(s.is_empty()); } From 7f366f6a310d5f3bb432bfe9edd37acd2d27b238 Mon Sep 17 00:00:00 2001 From: "Tom D." <15268361+anastygnome@users.noreply.github.com> Date: Thu, 12 Nov 2026 12:59:02 +0100 Subject: [PATCH 2/2] test(offset): cover named and normalized offsets --- tests/date.rs | 30 ++++++++++++++++++++++++++++++ tests/time.rs | 1 + 2 files changed, 31 insertions(+) diff --git a/tests/date.rs b/tests/date.rs index 0ef2f013..0caf3316 100644 --- a/tests/date.rs +++ b/tests/date.rs @@ -330,6 +330,36 @@ fn test_zone_abbreviation_offsets(#[case] input: &str, #[case] expected: &str) { check_absolute(input, expected); } +// GNU-compatible Australian zone abbreviations are accepted as fixed offsets +// even when the process timezone is UTC. +#[rstest] +#[case::aest("2026-07-10 12:00 AEST", "2026-07-10 12:00:00+10:00")] +#[case::aedt("2026-01-10 12:00 AEDT", "2026-01-10 12:00:00+11:00")] +#[case::acst("2026-07-10 12:00 ACST", "2026-07-10 12:00:00+09:30")] +#[case::acdt("2026-01-10 12:00 ACDT", "2026-01-10 12:00:00+10:30")] +#[case::awst("2026-01-10 12:00 AWST", "2026-01-10 12:00:00+08:00")] +fn test_australian_zone_abbreviation_offsets(#[case] input: &str, #[case] expected: &str) { + check_absolute(input, expected); +} + +// A named abbreviation matching the base IANA zone keeps that zone when a +// relative adjustment crosses a daylight-saving transition. +#[test] +fn test_named_zone_keeps_base_zone_across_dst() { + let base = "2026-01-01 00:00:00" + .parse::() + .unwrap() + .to_zoned_datetime(TimeZone::get("America/New_York").unwrap()) + .unwrap(); + + let parsed = parse_datetime::parse_datetime_at_date(base, "2026-03-07 12:00 EST 3 days") + .unwrap() + .expect_in_range(); + + assert_eq!(parsed.datetime().to_string(), "2026-03-10T13:00:00"); + assert_eq!(parsed.offset().seconds(), -4 * 3600); +} + // Regression test for uutils/coreutils#12555. // A fixed offset (e.g. the "UTC" keyword) must anchor the instant *before* // relative adjustments are applied. Otherwise, when the base zone observes DST, diff --git a/tests/time.rs b/tests/time.rs index b4f9e6bf..ff637338 100644 --- a/tests/time.rs +++ b/tests/time.rs @@ -70,6 +70,7 @@ fn test_time_12h_format(#[case] input: &str, #[case] expected: &str) { #[case::corrected_minus_hours_only("12:34:56-09", "21:34:56.000000000")] #[case::corrected_plus_minutes("12:34:56+09:12", "03:22:56.000000000")] #[case::corrected_minus_minutes("12:34:56-09:26", "22:00:56.000000000")] +#[case::normalized_plus_minutes("12:34:56+00:60", "11:34:56.000000000")] #[case::corrected_plus_single_digit("12:34:56+9", "03:34:56.000000000")] #[case::corrected_minus_single_digit("12:34:56-9", "21:34:56.000000000")] #[case::with_space("12:34:56 -09:00", "21:34:56.000000000")]