Skip to main content

ggplot_rs/scale/
datetime.rs

1use crate::aes::Aesthetic;
2use crate::data::Value;
3
4use super::Scale;
5
6/// A break interval for a date/time axis.
7#[derive(Clone, Copy, Debug)]
8enum DateBreak {
9    /// A fixed number of seconds (seconds/minutes/hours/days/weeks).
10    Secs(f64),
11    /// A number of whole calendar months (years = 12 × n).
12    Months(u32),
13}
14
15/// Date/time scale — maps epoch seconds to [0, 1] and formats axis labels as dates.
16#[derive(Clone, Debug)]
17pub struct ScaleDateTime {
18    aesthetic: Aesthetic,
19    name: String,
20    min: f64,
21    max: f64,
22    trained: bool,
23    expand: (f64, f64),
24    date_breaks: Option<DateBreak>,
25    date_labels: Option<String>,
26    /// Locale for month/weekday names and default date formats.
27    locale: Option<crate::locale::Locale>,
28}
29
30/// Decomposed UTC date/time.
31struct DateParts {
32    year: i64,
33    month: u32,
34    day: u32,
35    hour: u32,
36    minute: u32,
37    second: u32,
38}
39
40/// Days since 1970-01-01 for a civil (Y, M, D) date — Howard Hinnant's algorithm.
41fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
42    let y = if m <= 2 { y - 1 } else { y };
43    let era = (if y >= 0 { y } else { y - 399 }) / 400;
44    let yoe = y - era * 400;
45    let mp = if m > 2 { m - 3 } else { m + 9 } as i64;
46    let doy = (153 * mp + 2) / 5 + d as i64 - 1;
47    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
48    era * 146_097 + doe - 719_468
49}
50
51fn secs_from_civil(y: i64, m: u32, d: u32) -> i64 {
52    days_from_civil(y, m, d) * 86_400
53}
54
55/// Inverse of `days_from_civil`, plus the intra-day time.
56fn civil_from_secs(secs: i64) -> DateParts {
57    let (mut days, rem) = if secs >= 0 {
58        (secs / 86_400, secs % 86_400)
59    } else {
60        let d = (secs - 86_400 + 1) / 86_400;
61        (d, secs - d * 86_400)
62    };
63    let hour = (rem / 3600) as u32;
64    let minute = ((rem % 3600) / 60) as u32;
65    let second = (rem % 60) as u32;
66
67    days += 719_468;
68    let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
69    let doe = (days - era * 146_097) as u32;
70    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
71    let y = yoe as i64 + era * 400;
72    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
73    let mp = (5 * doy + 2) / 153;
74    let day = doy - (153 * mp + 2) / 5 + 1;
75    let month = if mp < 10 { mp + 3 } else { mp - 9 };
76    let year = if month <= 2 { y + 1 } else { y };
77    DateParts {
78        year,
79        month,
80        day,
81        hour,
82        minute,
83        second,
84    }
85}
86
87const MONTHS_SHORT: [&str; 12] = [
88    "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
89];
90const MONTHS_LONG: [&str; 12] = [
91    "January",
92    "February",
93    "March",
94    "April",
95    "May",
96    "June",
97    "July",
98    "August",
99    "September",
100    "October",
101    "November",
102    "December",
103];
104const DAYS_SHORT: [&str; 7] = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
105const DAYS_LONG: [&str; 7] = [
106    "Sunday",
107    "Monday",
108    "Tuesday",
109    "Wednesday",
110    "Thursday",
111    "Friday",
112    "Saturday",
113];
114
115/// Format a timestamp with a strftime-style subset:
116/// `%Y %y %m %-m %b %B %d %-d %e %a %A %H %M %S %%`.
117#[cfg(test)]
118fn strftime(secs: f64, fmt: &str) -> String {
119    strftime_locale(secs, fmt, None)
120}
121
122/// [`strftime`] with the month / weekday names of `locale` (English without).
123pub(crate) fn strftime_locale(
124    secs: f64,
125    fmt: &str,
126    locale: Option<&crate::locale::Locale>,
127) -> String {
128    let p = civil_from_secs(secs as i64);
129    let mi = (p.month.clamp(1, 12) - 1) as usize;
130    // 1970-01-01 was a Thursday (index 4, Sunday = 0).
131    let wd = ((secs as i64).div_euclid(86_400) + 4).rem_euclid(7) as usize;
132    let month_short = locale.map_or(MONTHS_SHORT[mi], |l| l.months_short[mi].as_str());
133    let month_long = locale.map_or(MONTHS_LONG[mi], |l| l.months_long[mi].as_str());
134    let day_short = locale.map_or(DAYS_SHORT[wd], |l| l.days_short[wd].as_str());
135    let day_long = locale.map_or(DAYS_LONG[wd], |l| l.days_long[wd].as_str());
136    let mut out = String::new();
137    let mut chars = fmt.chars().peekable();
138    while let Some(c) = chars.next() {
139        if c != '%' {
140            out.push(c);
141            continue;
142        }
143        match chars.next() {
144            Some('Y') => out.push_str(&format!("{:04}", p.year)),
145            Some('y') => out.push_str(&format!("{:02}", p.year.rem_euclid(100))),
146            Some('m') => out.push_str(&format!("{:02}", p.month)),
147            Some('b') => out.push_str(month_short),
148            Some('B') => out.push_str(month_long),
149            Some('a') => out.push_str(day_short),
150            Some('A') => out.push_str(day_long),
151            Some('d') => out.push_str(&format!("{:02}", p.day)),
152            Some('e') => out.push_str(&format!("{:2}", p.day)),
153            Some('H') => out.push_str(&format!("{:02}", p.hour)),
154            Some('M') => out.push_str(&format!("{:02}", p.minute)),
155            Some('S') => out.push_str(&format!("{:02}", p.second)),
156            Some('%') => out.push('%'),
157            // glibc's "no padding" flag: %-d, %-m.
158            Some('-') if matches!(chars.peek(), Some('d' | 'm')) => match chars.next() {
159                Some('d') => out.push_str(&p.day.to_string()),
160                _ => out.push_str(&p.month.to_string()),
161            },
162            Some(other) => {
163                out.push('%');
164                out.push(other);
165            }
166            None => out.push('%'),
167        }
168    }
169    out
170}
171
172/// Parse an R-style break spec like "1 month", "3 months", "2 weeks", "1 year".
173fn parse_date_break(spec: &str) -> Option<DateBreak> {
174    let spec = spec.trim().to_lowercase();
175    let mut parts = spec.split_whitespace();
176    let first = parts.next()?;
177    let (n, unit) = match first.parse::<f64>() {
178        Ok(n) => (n, parts.next()?.to_string()),
179        Err(_) => (1.0, first.to_string()),
180    };
181    let unit = unit.trim_end_matches('s');
182    let secs = |s: f64| Some(DateBreak::Secs(n * s));
183    match unit {
184        "sec" | "second" => secs(1.0),
185        "min" | "minute" => secs(60.0),
186        "hour" => secs(3600.0),
187        "day" => secs(86_400.0),
188        "week" => secs(604_800.0),
189        "month" => Some(DateBreak::Months(n.max(1.0) as u32)),
190        "year" => Some(DateBreak::Months((n.max(1.0) as u32) * 12)),
191        _ => None,
192    }
193}
194
195impl ScaleDateTime {
196    pub fn new() -> Self {
197        ScaleDateTime {
198            aesthetic: Aesthetic::X,
199            name: String::new(),
200            min: f64::INFINITY,
201            max: f64::NEG_INFINITY,
202            trained: false,
203            expand: (0.05, 0.0),
204            date_breaks: None,
205            date_labels: None,
206            locale: None,
207        }
208    }
209
210    pub fn for_aesthetic(mut self, aes: Aesthetic) -> Self {
211        self.aesthetic = aes;
212        self
213    }
214
215    pub fn with_name(mut self, name: &str) -> Self {
216        self.name = name.to_string();
217        self
218    }
219
220    /// Calendar-aware break interval, R-style: `"1 month"`, `"3 months"`,
221    /// `"2 weeks"`, `"1 year"`, `"6 hours"`, … Unrecognised specs are ignored.
222    pub fn with_date_breaks(mut self, spec: &str) -> Self {
223        self.date_breaks = parse_date_break(spec);
224        self
225    }
226
227    /// strftime-style label format, e.g. `"%b %Y"` or `"%Y-%m-%d"`.
228    /// Supported: `%Y %y %m %-m %b %B %d %-d %e %a %A %H %M %S %%`; month and
229    /// weekday names follow the scale's locale (English without one).
230    pub fn with_date_labels(mut self, fmt: &str) -> Self {
231        self.date_labels = Some(fmt.to_string());
232        self
233    }
234
235    /// Localise month / weekday names and the default date labels: with
236    /// de-DE, monthly breaks read `Okt. 2026` (instead of `2026-10`) and daily
237    /// breaks `15. Okt. 2026` (instead of `2026-10-15`). Overrides the plot
238    /// locale ([`GGPlot::locale`](crate::GGPlot::locale)).
239    pub fn with_locale(mut self, locale: crate::locale::Locale) -> Self {
240        self.locale = Some(locale);
241        self
242    }
243
244    fn label(&self, secs: f64, step: f64) -> String {
245        match (&self.date_labels, &self.locale) {
246            (Some(fmt), loc) => strftime_locale(secs, fmt, loc.as_ref()),
247            (None, Some(loc)) => loc.format_datetime(secs as i64),
248            (None, None) => Self::format_datetime(secs, step),
249        }
250    }
251
252    /// Default label of an auto month-step break (`2026-10`, or the locale's
253    /// [`month_format`](crate::locale::Locale::month_format)).
254    fn month_label(&self, y: i64, m: u32, secs: f64) -> String {
255        if let Some(fmt) = &self.date_labels {
256            return strftime_locale(secs, fmt, self.locale.as_ref());
257        }
258        match &self.locale {
259            Some(loc) => strftime_locale(secs, &loc.month_format, Some(loc)),
260            None => format!("{y:04}-{m:02}"),
261        }
262    }
263
264    /// Label of an auto year-step break: `with_date_labels` when set, else `2026`.
265    fn year_label(&self, y: i64, secs: f64) -> String {
266        match &self.date_labels {
267            Some(fmt) => strftime_locale(secs, fmt, self.locale.as_ref()),
268            None => format!("{y}"),
269        }
270    }
271
272    fn expanded_range(&self) -> (f64, f64) {
273        let range = self.max - self.min;
274        let mult = self.expand.0;
275        let add = self.expand.1;
276        (self.min - range * mult - add, self.max + range * mult + add)
277    }
278
279    /// Choose a "nice" step size in seconds for date/time breaks.
280    fn nice_datetime_step(range_secs: f64) -> f64 {
281        const MINUTE: f64 = 60.0;
282        const HOUR: f64 = 3600.0;
283        const DAY: f64 = 86400.0;
284        const WEEK: f64 = 7.0 * DAY;
285        const MONTH: f64 = 30.0 * DAY;
286        const YEAR: f64 = 365.25 * DAY;
287
288        let candidates = [
289            1.0,
290            5.0,
291            10.0,
292            30.0,
293            MINUTE,
294            5.0 * MINUTE,
295            10.0 * MINUTE,
296            30.0 * MINUTE,
297            HOUR,
298            3.0 * HOUR,
299            6.0 * HOUR,
300            12.0 * HOUR,
301            DAY,
302            2.0 * DAY,
303            WEEK,
304            2.0 * WEEK,
305            MONTH,
306            3.0 * MONTH,
307            6.0 * MONTH,
308            YEAR,
309            2.0 * YEAR,
310            5.0 * YEAR,
311            10.0 * YEAR,
312            20.0 * YEAR,
313            50.0 * YEAR,
314            100.0 * YEAR,
315        ];
316
317        let target = range_secs / 5.0;
318        for &c in &candidates {
319            if c >= target {
320                return c;
321            }
322        }
323        // For very large ranges, use multiples of 100 years
324        let n = (target / (100.0 * YEAR)).ceil();
325        n * 100.0 * YEAR
326    }
327
328    /// Format a timestamp (epoch seconds) as a human-readable label,
329    /// adapting precision to the break step size.
330    fn format_datetime(secs: f64, _step: f64) -> String {
331        let epoch_secs = secs as i64;
332        crate::data::format_epoch_secs(epoch_secs)
333    }
334}
335
336impl Default for ScaleDateTime {
337    fn default() -> Self {
338        Self::new()
339    }
340}
341
342impl Scale for ScaleDateTime {
343    fn set_default_locale(&mut self, locale: &crate::locale::Locale) {
344        if self.locale.is_none() {
345            self.locale = Some(locale.clone());
346        }
347    }
348
349    fn locale(&self) -> Option<&crate::locale::Locale> {
350        self.locale.as_ref()
351    }
352
353    fn format_value(&self, value: &Value) -> Option<String> {
354        let f = value.as_f64()?;
355        if !f.is_finite() {
356            return None;
357        }
358        // Review PR#141 finding 5: honour `with_date_labels` (and locale)
359        // the same way the axis break labels already do, via the shared
360        // `label` helper — not just the bare ISO/locale-date fallback.
361        // `label`'s `step` parameter only affects the no-format/no-locale
362        // branch's precision choice, which is irrelevant for a single
363        // point value, so 0.0 is fine.
364        Some(self.label(f, 0.0))
365    }
366
367    fn aesthetic(&self) -> Aesthetic {
368        self.aesthetic.clone()
369    }
370
371    fn train(&mut self, values: &[Value]) {
372        for v in values {
373            if let Some(f) = v.as_f64() {
374                if f.is_finite() {
375                    if f < self.min {
376                        self.min = f;
377                    }
378                    if f > self.max {
379                        self.max = f;
380                    }
381                }
382            }
383        }
384        self.trained = true;
385    }
386
387    fn map(&self, value: &Value) -> f64 {
388        let f = match value.as_f64() {
389            Some(f) => f,
390            None => return 0.0,
391        };
392        // ±Inf means "panel edge" (ggplot2): -Inf → lower edge, +Inf → upper.
393        if f == f64::INFINITY {
394            return 1.0;
395        }
396        if f == f64::NEG_INFINITY {
397            return 0.0;
398        }
399        // An untrained scale (empty data) has no domain — centre everything
400        // rather than producing NaN.
401        if !self.trained || !self.min.is_finite() || !self.max.is_finite() {
402            return 0.5;
403        }
404        let (emin, emax) = self.expanded_range();
405        let range = emax - emin;
406        if range.abs() < f64::EPSILON {
407            0.5
408        } else {
409            (f - emin) / range
410        }
411    }
412
413    fn domain(&self) -> Option<(f64, f64)> {
414        if self.trained && self.min.is_finite() && self.max.is_finite() {
415            Some((self.min, self.max))
416        } else {
417            None
418        }
419    }
420
421    fn expanded_domain(&self) -> Option<(f64, f64)> {
422        if !self.trained || !self.min.is_finite() || !self.max.is_finite() {
423            return None;
424        }
425        let (a, b) = self.expanded_range();
426        if !(a.is_finite() && b.is_finite()) {
427            return None;
428        }
429        if (b - a).abs() < f64::EPSILON {
430            // A degenerate domain maps everything to the panel centre.
431            return Some((a - 0.5, b + 0.5));
432        }
433        Some((a, b))
434    }
435
436    fn breaks(&self) -> Vec<(f64, String)> {
437        if !self.trained || self.min > self.max {
438            return vec![];
439        }
440
441        let range = self.max - self.min;
442        if super::util::is_degenerate_range(self.min, self.max) {
443            return vec![(0.5, self.label(self.min, 1.0))];
444        }
445
446        let (emin, emax) = self.expanded_range();
447        // Beyond ~±31,700 years the civil-calendar arithmetic below would
448        // overflow i64; such values are corrupt data, so draw no breaks.
449        const MAX_ABS_SECS: f64 = 1e12;
450        if !(emin.abs() <= MAX_ABS_SECS && emax.abs() <= MAX_ABS_SECS) {
451            return vec![];
452        }
453
454        // Calendar-month breaks snap to the first of the month.
455        if let Some(DateBreak::Months(n)) = self.date_breaks {
456            let n = n.max(1);
457            let start = civil_from_secs(emin.ceil() as i64);
458            let (mut y, mut m) = (start.year, start.month);
459            // First-of-month boundary at or after emin.
460            if (secs_from_civil(y, m, 1) as f64) < emin {
461                m += 1;
462                if m > 12 {
463                    m = 1;
464                    y += 1;
465                }
466            }
467            let mut breaks = Vec::new();
468            let mut guard = 0;
469            loop {
470                let secs = secs_from_civil(y, m, 1) as f64;
471                if secs > emax + 1.0 || guard > 10_000 {
472                    break;
473                }
474                breaks.push((self.map(&Value::Float(secs)), self.label(secs, 0.0)));
475                m += n;
476                while m > 12 {
477                    m -= 12;
478                    y += 1;
479                }
480                guard += 1;
481            }
482            return breaks;
483        }
484
485        let explicit_secs = matches!(self.date_breaks, Some(DateBreak::Secs(s)) if s > 0.0);
486        let step = match self.date_breaks {
487            Some(DateBreak::Secs(s)) if s > 0.0 => s,
488            _ => Self::nice_datetime_step(range),
489        };
490
491        // For month-or-larger auto steps, snap breaks to calendar boundaries with
492        // clean year / year-month labels (ggplot2-style) instead of fixed-second
493        // timestamps that drift off midnight (e.g. "2012-01-01 12:00:00").
494        const DAY: f64 = 86_400.0;
495        const MONTH: f64 = 30.0 * DAY;
496        const YEAR: f64 = 365.25 * DAY;
497        if !explicit_secs && step >= 0.9 * YEAR {
498            let n = ((step / YEAR).round() as i64).max(1);
499            let mut y = civil_from_secs(emin.ceil() as i64).year.div_euclid(n) * n;
500            while (secs_from_civil(y, 1, 1) as f64) < emin {
501                y += n;
502            }
503            let mut breaks = Vec::new();
504            while (secs_from_civil(y, 1, 1) as f64) <= emax + 1.0 {
505                let secs = secs_from_civil(y, 1, 1) as f64;
506                breaks.push((self.map(&Value::Float(secs)), self.year_label(y, secs)));
507                y += n;
508            }
509            return breaks;
510        }
511        if !explicit_secs && step >= 0.9 * MONTH {
512            let n = ((step / MONTH).round() as i64).max(1);
513            let start = civil_from_secs(emin.ceil() as i64);
514            let mut tm = start.year * 12 + (start.month as i64 - 1); // months since year 0
515            while (secs_from_civil(tm.div_euclid(12), tm.rem_euclid(12) as u32 + 1, 1) as f64)
516                < emin
517            {
518                tm += 1;
519            }
520            let mut breaks = Vec::new();
521            let mut guard = 0;
522            loop {
523                let (y, m) = (tm.div_euclid(12), tm.rem_euclid(12) as u32 + 1);
524                let secs = secs_from_civil(y, m, 1) as f64;
525                if secs > emax + 1.0 || guard > 10_000 {
526                    break;
527                }
528                breaks.push((self.map(&Value::Float(secs)), self.month_label(y, m, secs)));
529                tm += n;
530                guard += 1;
531            }
532            return breaks;
533        }
534
535        let start = (emin / step).ceil() * step;
536        super::util::stepped_breaks(start, emax, step)
537            .into_iter()
538            .map(|v| (self.map(&Value::Float(v)), self.label(v, step)))
539            .collect()
540    }
541
542    fn name(&self) -> &str {
543        &self.name
544    }
545
546    fn set_name(&mut self, name: &str) {
547        self.name = name.to_string();
548    }
549
550    fn set_limits(&mut self, min: f64, max: f64) {
551        self.min = min;
552        self.max = max;
553        self.trained = true;
554    }
555
556    fn clone_box(&self) -> Box<dyn Scale> {
557        Box::new(self.clone())
558    }
559
560    fn reset_training(&mut self) {
561        self.min = f64::INFINITY;
562        self.max = f64::NEG_INFINITY;
563        self.trained = false;
564    }
565}
566
567#[cfg(test)]
568mod tests {
569    use super::*;
570
571    #[test]
572    fn format_value_is_plain_iso_without_a_locale_and_locale_formatted_with_one() {
573        let s = ScaleDateTime::new();
574        // 2026-10-12T00:00:00Z.
575        assert_eq!(
576            s.format_value(&Value::Float(1_791_763_200.0)),
577            Some("2026-10-12".to_string())
578        );
579        assert_eq!(s.format_value(&Value::Float(f64::NAN)), None);
580
581        let mut with_locale = ScaleDateTime::new();
582        with_locale.set_default_locale(&crate::locale::Locale::de_de());
583        let formatted = with_locale
584            .format_value(&Value::Float(1_791_763_200.0))
585            .unwrap();
586        assert_ne!(formatted, "2026-10-12");
587    }
588
589    #[test]
590    fn format_value_honours_with_date_labels() {
591        // Review PR#141 finding 5: format_value ignored with_date_labels
592        // entirely, always falling back to ISO/locale — the axis break
593        // labels (via the private `label` helper) already honoured it.
594        let s = ScaleDateTime::new().with_date_labels("%d.%m.%Y");
595        assert_eq!(
596            s.format_value(&Value::Float(1_791_763_200.0)), // 2026-10-12
597            Some("12.10.2026".to_string())
598        );
599    }
600
601    #[test]
602    fn auto_month_and_year_breaks_honour_with_date_labels() {
603        // #352: the calendar-aware month/year branches labelled breaks
604        // themselves and ignored `with_date_labels`.
605        let monthly = |fmt: Option<&str>| {
606            let mut s = ScaleDateTime::new();
607            if let Some(f) = fmt {
608                s = s.with_date_labels(f);
609            }
610            // 18 monthly dates, 2025-01 … 2026-06.
611            let vals: Vec<Value> = (0..18)
612                .map(
613                    |i| Value::Float(secs_from_civil(2025 + i / 12, (i % 12) as u32 + 1, 1) as f64),
614                )
615                .collect();
616            s.train(&vals);
617            s.breaks().into_iter().map(|(_, l)| l).collect::<Vec<_>>()
618        };
619        assert_eq!(monthly(None), vec!["2025-01", "2025-07", "2026-01"]);
620        assert_eq!(
621            monthly(Some("%b %Y")),
622            vec!["Jan 2025", "Jul 2025", "Jan 2026"]
623        );
624        assert_eq!(monthly(Some("%b")), vec!["Jan", "Jul", "Jan"]);
625
626        let yearly = |fmt: Option<&str>| {
627            let mut s = ScaleDateTime::new();
628            if let Some(f) = fmt {
629                s = s.with_date_labels(f);
630            }
631            let vals: Vec<Value> = (2010..2021)
632                .map(|y| Value::Float(secs_from_civil(y, 1, 1) as f64))
633                .collect();
634            s.train(&vals);
635            s.breaks().into_iter().map(|(_, l)| l).collect::<Vec<_>>()
636        };
637        let plain = yearly(None);
638        assert!(
639            !plain.is_empty() && plain.iter().all(|l| l.len() == 4),
640            "{plain:?}"
641        );
642        assert_eq!(yearly(Some("%Y")), plain);
643        assert_eq!(
644            yearly(Some("%b %Y")),
645            plain.iter().map(|y| format!("Jan {y}")).collect::<Vec<_>>()
646        );
647    }
648
649    #[test]
650    fn civil_roundtrip() {
651        // 2021-03-15 12:30:45 UTC = 1615811445
652        let p = civil_from_secs(1_615_811_445);
653        assert_eq!((p.year, p.month, p.day), (2021, 3, 15));
654        assert_eq!((p.hour, p.minute, p.second), (12, 30, 45));
655        assert_eq!(secs_from_civil(2021, 3, 15), 1_615_766_400); // midnight
656    }
657
658    #[test]
659    fn multiyear_default_breaks_are_clean_years() {
660        // A multi-year range with no explicit date_breaks should snap to calendar
661        // year boundaries and label with plain years (not drifting timestamps).
662        let mut s = ScaleDateTime::new();
663        s.train(&[
664            Value::DateTime(secs_from_civil(2011, 2, 1)),
665            Value::DateTime(secs_from_civil(2016, 4, 1)),
666        ]);
667        let labels: Vec<String> = s.breaks().into_iter().map(|(_, l)| l).collect();
668        assert!(!labels.is_empty());
669        for l in &labels {
670            assert!(
671                l.len() == 4 && l.chars().all(|c| c.is_ascii_digit()),
672                "expected a bare year label, got {l:?}"
673            );
674        }
675        assert!(labels.contains(&"2014".to_string()));
676    }
677
678    #[test]
679    fn strftime_subset() {
680        let s = 1_615_766_400.0; // 2021-03-15 00:00
681        assert_eq!(strftime(s, "%Y-%m-%d"), "2021-03-15");
682        assert_eq!(strftime(s, "%b %Y"), "Mar 2021");
683        assert_eq!(strftime(s, "%B"), "March");
684        assert_eq!(strftime(s, "100%%"), "100%");
685    }
686
687    #[test]
688    fn strftime_weekdays_and_unpadded() {
689        let s = 1_615_766_400.0; // 2021-03-15 00:00, a Monday
690        assert_eq!(strftime(s, "%a %A"), "Mon Monday");
691        assert_eq!(strftime(s - 86_400.0 * 10.0, "%-d.%-m. %d"), "5.3. 05");
692        assert_eq!(strftime(s, "%-x"), "%-x");
693        assert_eq!(strftime(-86_400.0, "%a"), "Wed"); // 1969-12-31
694    }
695
696    #[test]
697    fn locale_month_and_day_labels() {
698        let de = crate::locale::Locale::de_de();
699        // Auto monthly breaks: "Okt. 2026" instead of "2026-10".
700        let mut s = ScaleDateTime::new().with_locale(de.clone());
701        s.set_limits(
702            secs_from_civil(2026, 7, 1) as f64,
703            secs_from_civil(2027, 2, 1) as f64,
704        );
705        let labels: Vec<String> = s.breaks().into_iter().map(|(_, l)| l).collect();
706        assert!(labels.contains(&"Okt. 2026".to_string()), "{labels:?}");
707        assert!(labels.contains(&"Jan. 2027".to_string()), "{labels:?}");
708        // Same scale without locale: unchanged ISO labels.
709        let mut plain = ScaleDateTime::new();
710        plain.set_limits(
711            secs_from_civil(2026, 7, 1) as f64,
712            secs_from_civil(2027, 2, 1) as f64,
713        );
714        let labels: Vec<String> = plain.breaks().into_iter().map(|(_, l)| l).collect();
715        assert!(labels.contains(&"2026-10".to_string()), "{labels:?}");
716        // Explicit format: localized names.
717        let mut f = ScaleDateTime::new()
718            .with_date_labels("%B")
719            .with_date_breaks("1 month");
720        f.set_default_locale(&de);
721        f.set_limits(
722            secs_from_civil(2026, 2, 20) as f64,
723            secs_from_civil(2026, 4, 2) as f64,
724        );
725        let labels: Vec<String> = f.breaks().into_iter().map(|(_, l)| l).collect();
726        assert_eq!(labels, ["März", "April"]);
727        // Day-level default labels.
728        let mut d = ScaleDateTime::new().with_locale(de);
729        d.set_limits(
730            secs_from_civil(2026, 10, 12) as f64,
731            secs_from_civil(2026, 10, 16) as f64,
732        );
733        let labels: Vec<String> = d.breaks().into_iter().map(|(_, l)| l).collect();
734        assert!(labels.contains(&"15. Okt. 2026".to_string()), "{labels:?}");
735        // A scale's own locale beats the plot default.
736        let mut own = ScaleDateTime::new().with_locale(crate::locale::Locale::fr_fr());
737        own.set_default_locale(&crate::locale::Locale::de_de());
738        assert_eq!(own.locale().unwrap().tag, "fr-FR");
739    }
740
741    #[test]
742    fn parse_specs() {
743        assert!(matches!(
744            parse_date_break("1 month"),
745            Some(DateBreak::Months(1))
746        ));
747        assert!(matches!(
748            parse_date_break("3 months"),
749            Some(DateBreak::Months(3))
750        ));
751        assert!(matches!(
752            parse_date_break("1 year"),
753            Some(DateBreak::Months(12))
754        ));
755        assert!(
756            matches!(parse_date_break("2 weeks"), Some(DateBreak::Secs(s)) if s == 1_209_600.0)
757        );
758        assert!(matches!(
759            parse_date_break("month"),
760            Some(DateBreak::Months(1))
761        ));
762        assert!(parse_date_break("fortnight").is_none());
763    }
764
765    #[test]
766    fn monthly_breaks_land_on_first_of_month() {
767        let mut s = ScaleDateTime::new()
768            .with_date_breaks("1 month")
769            .with_date_labels("%Y-%m-%d");
770        // Jan 10 2021 .. Apr 20 2021
771        s.set_limits(
772            secs_from_civil(2021, 1, 10) as f64,
773            secs_from_civil(2021, 4, 20) as f64,
774        );
775        let labels: Vec<String> = s.breaks().into_iter().map(|(_, l)| l).collect();
776        assert!(labels.iter().all(|l| l.ends_with("-01")), "{labels:?}");
777        assert!(labels.contains(&"2021-02-01".to_string()));
778    }
779}