diff --git a/crates/core/src/date.rs b/crates/core/src/date.rs index b61892f6c..cc875d66c 100644 --- a/crates/core/src/date.rs +++ b/crates/core/src/date.rs @@ -139,6 +139,43 @@ pub fn serial_from_ymd(sys: DateSystem, year: i64, month: i64, day: i64) -> Opti Some(serial as f64) } +/// The calendar date ISO 8601 text (pivot cache `` items, `t="d"` cells) gives a date of a +/// date system's calendar, as [`datetime_from_serial`] returns it. ISO dates count real days: +/// from 1899-12-30 in the 1900 system and from 1904-01-01 in the 1904 system. Up to February +/// 1900 the 1900 system's own calendar, with its day 1900-01-00 and the fictitious 1900-02-29, +/// runs one day ahead of that: serial 0 (the date part of a time) is 1899-12-30, serial 1 is +/// 1899-12-31 and serial 60 is 1900-02-28. Excel writes them that way. +pub fn iso_ymd(sys: DateSystem, year: i32, month: u32, day: u32) -> (i32, u32, u32) { + if sys == DateSystem::D1900 && year == 1900 && month <= 2 { + let serial = if month <= 1 { day } else { 31 + day }; + return civil_from_days(i64::from(serial) + UNIX_1899_12_30); + } + (year, month, day) +} + +/// Serial for an ISO 8601 calendar date, the inverse of [`iso_ymd`]. Unlike [`serial_from_ymd`] +/// (`DATE()`), years below 1900 aren't moved on by 1900 and month or day overflow is invalid. +/// The 1900 system also takes 1900-02-29 (serial 60), which some writers use for that day; the +/// 1904 system takes 1899-12-30 as the date part of a time (serial 0). `None` for an invalid date, +/// or one before the epoch or after 9999-12-31. +pub fn serial_from_iso_ymd(sys: DateSystem, year: i64, month: i64, day: i64) -> Option { + let (y, m, d) = (i32::try_from(year).ok()?, u32::try_from(month).ok()?, u32::try_from(day).ok()?); + match (sys, y, m, d) { + (DateSystem::D1900, 1900, 2, 29) => return Some(60.0), + (DateSystem::D1904, 1899, 12, 30) => return Some(0.0), + _ => {} + } + if !(1..=9999).contains(&y) || !(1..=12).contains(&m) || d < 1 || d > days_in_month(y, m) { + return None; + } + let base = match sys { + DateSystem::D1900 => UNIX_1899_12_30, + DateSystem::D1904 => UNIX_1904_01_01, + }; + let serial = days_from_civil(y, m, d) - base; + (0..=max_serial(sys)).contains(&serial).then_some(serial as f64) +} + /// Date/time from a serial. `None` for negative or too-large serials. pub fn datetime_from_serial(sys: DateSystem, serial: f64) -> Option { if !serial.is_finite() || !(0.0..max_serial(sys) as f64 + 1.0).contains(&serial) { @@ -286,4 +323,32 @@ mod tests { let d = datetime_from_serial(s, 1.0).unwrap(); assert_eq!(d.weekday, 0); // 1900-01-01 was a Sunday in Excel's calendar } + + #[test] + fn iso_dates_count_real_days() { + let s = DateSystem::D1900; + // Excel writes serial 0 (a time's date part) as 1899-12-30 and serial 1 as 1899-12-31. + for (serial, ymd) in + [(0, (1899, 12, 30)), (1, (1899, 12, 31)), (2, (1900, 1, 1)), (60, (1900, 2, 28)), (61, (1900, 3, 1)), (46302, (2026, 10, 7))] + { + let d = datetime_from_serial(s, serial as f64).unwrap(); + assert_eq!(iso_ymd(s, d.year, d.month, d.day), ymd, "{serial}"); + assert_eq!(serial_from_iso_ymd(s, ymd.0 as i64, ymd.1 as i64, ymd.2 as i64), Some(serial as f64), "{serial}"); + } + assert_eq!(serial_from_iso_ymd(s, 1900, 2, 29), Some(60.0)); + assert_eq!(serial_from_iso_ymd(s, 1899, 12, 29), None); + assert_eq!(serial_from_iso_ymd(s, 2024, 2, 30), None); + assert_eq!(serial_from_iso_ymd(s, 2024, 13, 1), None); + assert_eq!(serial_from_iso_ymd(s, 9999, 12, 31), Some(2958465.0)); + assert_eq!(serial_from_iso_ymd(s, 10000, 1, 1), None); + assert_eq!(serial_from_iso_ymd(s, i64::MAX, 1, 1), None); + // The 1904 system has no offset; 1899-12-30 stands for a time's date part there too. + let s = DateSystem::D1904; + let d = datetime_from_serial(s, 0.5).unwrap(); + assert_eq!(iso_ymd(s, d.year, d.month, d.day), (1904, 1, 1)); + assert_eq!(serial_from_iso_ymd(s, 1904, 1, 1), Some(0.0)); + assert_eq!(serial_from_iso_ymd(s, 1904, 3, 1), Some(60.0)); + assert_eq!(serial_from_iso_ymd(s, 1899, 12, 30), Some(0.0)); + assert_eq!(serial_from_iso_ymd(s, 1903, 12, 31), None); + } } diff --git a/crates/xlsx/src/pivot.rs b/crates/xlsx/src/pivot.rs index 06df26384..159afe5e2 100644 --- a/crates/xlsx/src/pivot.rs +++ b/crates/xlsx/src/pivot.rs @@ -14,7 +14,7 @@ use std::collections::HashMap; use std::fmt::Write as _; -use gridcraft_core::date::datetime_from_serial; +use gridcraft_core::date::{datetime_from_serial, iso_ymd}; use gridcraft_core::{CellRef, DateSystem, RangeRef, Value, number_to_text}; use gridcraft_formula::quote_sheet; use gridcraft_model::{ @@ -157,10 +157,11 @@ fn group_caption(g: PivotDateGroup) -> &'static str { } } -/// `2024-03-05T00:00:00` for a date serial. +/// `2024-03-05T00:00:00` for a date serial; a time alone is on `1899-12-30` (see [`iso_ymd`]). fn iso(sys: DateSystem, serial: f64) -> Option { let d = datetime_from_serial(sys, serial)?; - Some(format!("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}", d.year, d.month, d.day, d.hour, d.minute, d.second)) + let (y, m, day) = iso_ymd(sys, d.year, d.month, d.day); + Some(format!("{y:04}-{m:02}-{day:02}T{:02}:{:02}:{:02}", d.hour, d.minute, d.second)) } /// `3/5/2024` for a date serial (group boundary captions). diff --git a/crates/xlsx/src/sheet_read.rs b/crates/xlsx/src/sheet_read.rs index 0194d2268..ffc7c1643 100644 --- a/crates/xlsx/src/sheet_read.rs +++ b/crates/xlsx/src/sheet_read.rs @@ -3,7 +3,7 @@ use std::collections::HashMap; use std::sync::Arc; -use gridcraft_core::date::{serial_from_ymd, time_fraction}; +use gridcraft_core::date::{serial_from_iso_ymd, time_fraction}; use gridcraft_core::{CellError, CellRef, DateSystem, MAX_COLS, MAX_ROWS, RangeRef, Value}; use gridcraft_formula::Expr; use gridcraft_model::{ @@ -508,7 +508,8 @@ fn read_formula(cx: &mut Ctx<'_>, st: &mut RowState, f: &El, pos: CellRef, dynam } } -/// `2024-03-15`, `2024-03-15T10:30:00Z`, `10:30:00` → serial. +/// `2024-03-15`, `2024-03-15T10:30:00Z`, `10:30:00` → serial. Dates count real days from the +/// epoch, so `1899-12-30T08:00:00` is the time 8:00 (see [`serial_from_iso_ymd`]). pub fn parse_iso_datetime(s: &str, sys: DateSystem) -> Option { let s = s.trim_end_matches('Z'); let (date, time) = match s.split_once('T') { @@ -522,10 +523,7 @@ pub fn parse_iso_datetime(s: &str, sys: DateSystem) -> Option { let y: i64 = it.next()?.parse().ok()?; let m: i64 = it.next()?.parse().ok()?; let d: i64 = it.next()?.parse().ok()?; - if !(1..=12).contains(&m) || !(1..=31).contains(&d) { - return None; - } - serial = serial_from_ymd(sys, y, m, d)?; + serial = serial_from_iso_ymd(sys, y, m, d)?; } if let Some(t) = time { // Drop a time-zone offset. @@ -1007,7 +1005,10 @@ mod tests { #[test] fn iso_dates() { - assert_eq!(parse_iso_datetime("1900-01-01", DateSystem::D1900), Some(1.0)); + assert_eq!(parse_iso_datetime("1900-01-01", DateSystem::D1900), Some(2.0)); + assert_eq!(parse_iso_datetime("1899-12-31T12:30:00", DateSystem::D1900), Some(1.0 + time_fraction(12.0, 30.0, 0.0))); + assert_eq!(parse_iso_datetime("1899-12-30T08:00:00", DateSystem::D1900), Some(time_fraction(8.0, 0.0, 0.0))); + assert_eq!(parse_iso_datetime("1900-03-01", DateSystem::D1900), Some(61.0)); assert_eq!(parse_iso_datetime("2024-01-01T12:00:00Z", DateSystem::D1900), Some(45292.5)); assert_eq!(parse_iso_datetime("1904-01-02", DateSystem::D1904), Some(1.0)); assert_eq!(parse_iso_datetime("06:00:00", DateSystem::D1900), Some(0.25)); diff --git a/crates/xlsx/src/tests/pivot_tests.rs b/crates/xlsx/src/tests/pivot_tests.rs index ab0e14dc5..f8d2a34f6 100644 --- a/crates/xlsx/src/tests/pivot_tests.rs +++ b/crates/xlsx/src/tests/pivot_tests.rs @@ -629,6 +629,20 @@ fn manual_order_in_cache_order_is_kept() { assert_eq!(back.sheet(1).unwrap().pivots[0].columns[0].item_order, ["A", "B", "C"]); } +#[test] +fn early_dates_in_caches_count_real_days() { + // Excel writes serial 1 as 1899-12-31 (ISO dates count days from 1899-12-30), not as the + // 1900 calendar's 1900-01-01, which it reads as serial 2. + let mut wb = workbook(); + let date_style = wb.sheet(0).unwrap().cells.get(at("C2")).unwrap().style; + wb.sheet_mut(0).unwrap().cells.set(at("C2"), Cell { value: Value::number(1.5), formula: None, style: date_style }); + let parts = unzip(&write_xlsx(&wb).unwrap()); + let caches: String = + parts.iter().filter(|(k, _)| k.contains("pivotCacheDefinition")).map(|(_, v)| String::from_utf8_lossy(v).into_owned()).collect(); + assert!(caches.contains("minDate=\"1899-12-31T12:00:00\"") && caches.contains("startDate=\"1899-12-31T00:00:00\""), "{caches}"); + assert!(!caches.contains("1900-01-01T"), "{caches}"); +} + #[test] fn location_without_field_headers_has_no_values_row() { let mut wb = workbook();