Skip to main content

dateoxide_core/
time_spans.rs

1use crate::relative::apply_relative_offset;
2use crate::locale::TimeUnit;
3use crate::settings::{Settings, StartOfWeek};
4use chrono::{Datelike, Duration, NaiveDateTime};
5use regex::Regex;
6use std::sync::OnceLock;
7
8#[derive(Debug, Clone)]
9pub struct TimeSpanMatch {
10    pub span_type: &'static str,
11    pub direction: &'static str,
12    pub number: Option<u32>,
13    pub matched_text: String,
14    pub start_pos: usize,
15    pub end_pos: usize,
16}
17
18struct CompiledSpanPattern {
19    regex: Regex,
20    span_type: &'static str,
21    direction: &'static str,
22    has_num: bool,
23}
24
25static SPAN_PATTERNS: OnceLock<Vec<CompiledSpanPattern>> = OnceLock::new();
26
27fn patterns() -> &'static [CompiledSpanPattern] {
28    SPAN_PATTERNS.get_or_init(|| {
29        let specs = [
30            // English
31            (r"(?i)\b(?:for\s+the\s+|during\s+the\s+|in\s+the\s+)?(?:past|last|previous)\s+month\b", "month", "past", false),
32            (r"(?i)\b(?:for\s+the\s+|during\s+the\s+|in\s+the\s+)?(?:past|last|previous)\s+week\b", "week", "past", false),
33            (r"(?i)\b(?:for\s+the\s+|during\s+the\s+|in\s+the\s+)?(?:past|last|previous)\s+(\d+)\s+days?\b", "days", "past", true),
34            (r"(?i)\b(?:for\s+the\s+|during\s+the\s+|in\s+the\s+)?(?:past|last|previous)\s+(\d+)\s+weeks?\b", "weeks", "past", true),
35            (r"(?i)\b(?:for\s+the\s+|during\s+the\s+|in\s+the\s+)?(?:past|last|previous)\s+(\d+)\s+months?\b", "months", "past", true),
36            (r"(?i)\b(?:for\s+the\s+|during\s+the\s+|in\s+the\s+)?(?:next|coming|following)\s+month\b", "month", "future", false),
37            (r"(?i)\b(?:for\s+the\s+|during\s+the\s+|in\s+the\s+)?(?:next|coming|following)\s+week\b", "week", "future", false),
38            (r"(?i)\b(?:for\s+the\s+|during\s+the\s+|in\s+the\s+)?(?:next|coming|following)\s+(\d+)\s+days?\b", "days", "future", true),
39            (r"(?i)\b(?:for\s+the\s+|during\s+the\s+|in\s+the\s+)?(?:next|coming|following)\s+(\d+)\s+weeks?\b", "weeks", "future", true),
40            (r"(?i)\b(?:for\s+the\s+|during\s+the\s+|in\s+the\s+)?(?:next|coming|following)\s+(\d+)\s+months?\b", "months", "future", true),
41            // Turkish
42            (r"(?i)\b(?:geçen|gecen|önceki|onceki)\s+ay\b", "month", "past", false),
43            (r"(?i)\b(?:geçen|gecen|önceki|onceki)\s+hafta\b", "week", "past", false),
44            (r"(?i)\b(?:son|geçen|gecen)\s+(\d+)\s+(?:gün|gun)\b", "days", "past", true),
45            (r"(?i)\b(?:son|geçen|gecen)\s+(\d+)\s+hafta\b", "weeks", "past", true),
46            (r"(?i)\b(?:son|geçen|gecen)\s+(\d+)\s+ay\b", "months", "past", true),
47            (r"(?i)\b(?:gelecek|önümüzdeki|onumuzdeki|sonraki)\s+ay\b", "month", "future", false),
48            (r"(?i)\b(?:gelecek|önümüzdeki|onumuzdeki|sonraki)\s+hafta\b", "week", "future", false),
49            (r"(?i)\b(?:gelecek|önümüzdeki|onumuzdeki|sonraki)\s+(\d+)\s+(?:gün|gun)\b", "days", "future", true),
50            (r"(?i)\b(?:gelecek|önümüzdeki|onumuzdeki|sonraki)\s+(\d+)\s+hafta\b", "weeks", "future", true),
51            (r"(?i)\b(?:gelecek|önümüzdeki|onumuzdeki|sonraki)\s+(\d+)\s+ay\b", "months", "future", true),
52            // German
53            (r"(?i)\b(?:letzten?|vergangenen?)\s+monat\b", "month", "past", false),
54            (r"(?i)\bletzte\s+woche\b", "week", "past", false),
55            (r"(?i)\b(?:letzten?|vergangenen?)\s+(\d+)\s+tage?\b", "days", "past", true),
56            (r"(?i)\b(?:letzten?|vergangenen?)\s+(\d+)\s+wochen?\b", "weeks", "past", true),
57            (r"(?i)\b(?:letzten?|vergangenen?)\s+(\d+)\s+monate?\b", "months", "past", true),
58            (r"(?i)\b(?:nächsten?|naechsten?|kommenden?)\s+monat\b", "month", "future", false),
59            (r"(?i)\b(?:nächste|naechste|kommende)\s+woche\b", "week", "future", false),
60            (r"(?i)\b(?:nächsten?|naechsten?|kommenden?)\s+(\d+)\s+tage?\b", "days", "future", true),
61            (r"(?i)\b(?:nächsten?|naechsten?|kommenden?)\s+(\d+)\s+wochen?\b", "weeks", "future", true),
62            (r"(?i)\b(?:nächsten?|naechsten?|kommenden?)\s+(\d+)\s+monate?\b", "months", "future", true),
63            // French
64            (r"(?i)\b(?:mois\s+dernier|dernier\s+mois)\b", "month", "past", false),
65            (r"(?i)\b(?:semaine\s+dernière|semaine\s+derniere|dernière\s+semaine)\b", "week", "past", false),
66            (r"(?i)\b(?:(\d+)\s+derniers?\s+jours|derniers?\s+(\d+)\s+jours)\b", "days", "past", true),
67            (r"(?i)\b(?:(\d+)\s+dernières?\s+semaines|(\d+)\s+dernieres?\s+semaines)\b", "weeks", "past", true),
68            (r"(?i)\b(?:(\d+)\s+derniers?\s+mois)\b", "months", "past", true),
69            (r"(?i)\b(?:mois\s+prochain|prochain\s+mois)\b", "month", "future", false),
70            (r"(?i)\b(?:semaine\s+prochaine|prochaine\s+semaine)\b", "week", "future", false),
71            (r"(?i)\b(\d+)\s+prochains?\s+jours\b", "days", "future", true),
72            (r"(?i)\b(\d+)\s+prochaines?\s+semaines\b", "weeks", "future", true),
73            (r"(?i)\b(\d+)\s+prochains?\s+mois\b", "months", "future", true),
74            // Spanish
75            (r"(?i)\b(?:mes\s+pasado|último\s+mes|ultimo\s+mes)\b", "month", "past", false),
76            (r"(?i)\b(?:semana\s+pasada|última\s+semana|ultima\s+semana)\b", "week", "past", false),
77            (r"(?i)\b(?:últimos|ultimos|pasados)\s+(\d+)\s+(?:días|dias)\b", "days", "past", true),
78            (r"(?i)\b(?:últimas|ultimas|pasadas)\s+(\d+)\s+semanas\b", "weeks", "past", true),
79            (r"(?i)\b(?:últimos|ultimos|pasados)\s+(\d+)\s+meses\b", "months", "past", true),
80            (r"(?i)\b(?:próximo|proximo)\s+mes\b", "month", "future", false),
81            (r"(?i)\b(?:próxima|proxima)\s+semana\b", "week", "future", false),
82            (r"(?i)\b(?:próximos|proximos|siguientes)\s+(\d+)\s+(?:días|dias)\b", "days", "future", true),
83            (r"(?i)\b(?:próximas|proximas|siguientes)\s+(\d+)\s+semanas\b", "weeks", "future", true),
84            (r"(?i)\b(?:próximos|proximos|siguientes)\s+(\d+)\s+meses\b", "months", "future", true),
85        ];
86        specs
87            .into_iter()
88            .map(|(pat, span_type, direction, has_num)| CompiledSpanPattern {
89                regex: Regex::new(pat).expect("valid static span regex"),
90                span_type,
91                direction,
92                has_num,
93            })
94            .collect()
95    })
96}
97
98/// Detect time span expressions such as `"last week"`, `"past 3 days"`, `"next 2 months"`.
99pub fn detect_time_span(text: &str) -> Option<TimeSpanMatch> {
100    for pat in patterns() {
101        if let Some(caps) = pat.regex.captures(text) {
102            let full = caps.get(0)?;
103            let number = if pat.has_num {
104                let num_str = caps.iter().skip(1).flatten().next()?.as_str();
105                match num_str.parse::<u32>() {
106                    Ok(n) => Some(n),
107                    Err(_) => continue,
108                }
109            } else {
110                None
111            };
112            return Some(TimeSpanMatch {
113                span_type: pat.span_type,
114                direction: pat.direction,
115                number,
116                matched_text: full.as_str().to_string(),
117                start_pos: full.start(),
118                end_pos: full.end(),
119            });
120        }
121    }
122    None
123}
124
125fn week_start(date: NaiveDateTime, start_of_week: StartOfWeek) -> NaiveDateTime {
126    let mut days_back = date.weekday().num_days_from_monday() as i64;
127    if start_of_week != StartOfWeek::Monday {
128        days_back = (days_back + 1) % 7;
129    }
130    date - Duration::days(days_back)
131}
132
133/// Return `(start, end)` datetimes for a detected time span relative to `base_date`.
134pub fn generate_time_span(
135    span_type: &str,
136    direction: &str,
137    number: u32,
138    base_date: NaiveDateTime,
139    settings: &Settings,
140) -> Option<(NaiveDateTime, NaiveDateTime)> {
141    let past = direction == "past";
142    if span_type == "week" {
143        let ws = week_start(base_date, settings.default_start_of_week);
144        return if past {
145            Some((ws - Duration::days(7), ws - Duration::days(1)))
146        } else {
147            let start = ws + Duration::days(7);
148            Some((start, start + Duration::days(6)))
149        };
150    }
151
152    let sign: i8 = if past { -1 } else { 1 };
153    let other = match span_type {
154        "month" => apply_relative_offset(
155            base_date,
156            sign,
157            settings.default_days_in_month as f64,
158            TimeUnit::Day,
159        )?,
160        "days" => apply_relative_offset(base_date, sign, number as f64, TimeUnit::Day)?,
161        "weeks" => apply_relative_offset(base_date, sign, number as f64, TimeUnit::Week)?,
162        _ => apply_relative_offset(base_date, sign, number as f64, TimeUnit::Month)?,
163    };
164
165    if past {
166        Some((other, base_date))
167    } else {
168        Some((base_date, other))
169    }
170}