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            (r"(?i)\b(?:for\s+the\s+|during\s+the\s+|in\s+the\s+)?(?:past|last|previous)\s+month\b", "month", "past", false),
31            (r"(?i)\b(?:for\s+the\s+|during\s+the\s+|in\s+the\s+)?(?:past|last|previous)\s+week\b", "week", "past", false),
32            (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),
33            (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),
34            (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),
35            (r"(?i)\b(?:for\s+the\s+|during\s+the\s+|in\s+the\s+)?(?:next|coming|following)\s+month\b", "month", "future", false),
36            (r"(?i)\b(?:for\s+the\s+|during\s+the\s+|in\s+the\s+)?(?:next|coming|following)\s+week\b", "week", "future", false),
37            (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),
38            (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),
39            (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),
40        ];
41        specs
42            .into_iter()
43            .map(|(pat, span_type, direction, has_num)| CompiledSpanPattern {
44                regex: Regex::new(pat).expect("valid static span regex"),
45                span_type,
46                direction,
47                has_num,
48            })
49            .collect()
50    })
51}
52
53/// Detect time span expressions such as `"last week"`, `"past 3 days"`, `"next 2 months"`.
54pub fn detect_time_span(text: &str) -> Option<TimeSpanMatch> {
55    for pat in patterns() {
56        if let Some(caps) = pat.regex.captures(text) {
57            let full = caps.get(0)?;
58            let number = if pat.has_num {
59                let num_str = caps.get(1)?.as_str();
60                match num_str.parse::<u32>() {
61                    Ok(n) => Some(n),
62                    Err(_) => continue,
63                }
64            } else {
65                None
66            };
67            return Some(TimeSpanMatch {
68                span_type: pat.span_type,
69                direction: pat.direction,
70                number,
71                matched_text: full.as_str().to_string(),
72                start_pos: full.start(),
73                end_pos: full.end(),
74            });
75        }
76    }
77    None
78}
79
80fn week_start(date: NaiveDateTime, start_of_week: StartOfWeek) -> NaiveDateTime {
81    let mut days_back = date.weekday().num_days_from_monday() as i64;
82    if start_of_week != StartOfWeek::Monday {
83        days_back = (days_back + 1) % 7;
84    }
85    date - Duration::days(days_back)
86}
87
88/// Return `(start, end)` datetimes for a detected time span relative to `base_date`.
89pub fn generate_time_span(
90    span_type: &str,
91    direction: &str,
92    number: u32,
93    base_date: NaiveDateTime,
94    settings: &Settings,
95) -> Option<(NaiveDateTime, NaiveDateTime)> {
96    let past = direction == "past";
97    if span_type == "week" {
98        let ws = week_start(base_date, settings.default_start_of_week);
99        return if past {
100            Some((ws - Duration::days(7), ws - Duration::days(1)))
101        } else {
102            let start = ws + Duration::days(7);
103            Some((start, start + Duration::days(6)))
104        };
105    }
106
107    let sign: i8 = if past { -1 } else { 1 };
108    let other = match span_type {
109        "month" => apply_relative_offset(
110            base_date,
111            sign,
112            settings.default_days_in_month as f64,
113            TimeUnit::Day,
114        )?,
115        "days" => apply_relative_offset(base_date, sign, number as f64, TimeUnit::Day)?,
116        "weeks" => apply_relative_offset(base_date, sign, number as f64, TimeUnit::Week)?,
117        _ => apply_relative_offset(base_date, sign, number as f64, TimeUnit::Month)?,
118    };
119
120    if past {
121        Some((other, base_date))
122    } else {
123        Some((base_date, other))
124    }
125}