date_filter_search 0.1.1

Date Filter Search is a Rust library that makes working with dates a breeze. It seamlessly converts dates to Unix seconds and Unix seconds back to dates, validates and completes partial date inputs, supports a configurable time zone (Local or UTC), and features robust parsing of both absolute and relative search strings for powerful date filtering.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
use chrono::{Datelike, Local, Timelike, Utc};
use once_cell::sync::OnceCell;
use regex::Regex;
use std::error::Error;
use std::fmt;

const YEAR_START: u16 = 1970;
const YEAR_END: u16 = 2100;

const UNIT_SECONDS: &str = "s";
const UNIT_MINUTES: &str = "m";
const UNIT_HOURS: &str = "h";
const UNIT_DAYS: &str = "D";
const UNIT_MONTHS: &str = "M";
const UNIT_YEARS: &str = "Y";

const UNIT_DELIMITER: &str = "to";

/// Structure representing a custom date and time.
#[derive(Debug)]
pub struct DateTime {
    year: u16,
    month: u8,
    day: u8,
    hour: u8,
    minute: u8,
    second: u8,
}

/// Enum to choose the time zone.
#[derive(Debug, Copy, Clone)]
pub enum TimeZoneOption {
    Local,
    Utc,
}

/// Enum representing errors related to date operations.
#[derive(Debug)]
pub enum DateError {
    EmptyInput,
    InvalidDateFormat,
    InvalidRegex,
    OutOfRange(String),
    ParsingError(String),
    IncorrectUnit(String),
}

impl fmt::Display for DateError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let msg = match self {
            DateError::EmptyInput => "The input provided is empty.",
            DateError::InvalidDateFormat => "The date format is invalid.",
            DateError::InvalidRegex => "The regex pattern format is incorrect.",
            DateError::OutOfRange(detail) => return write!(f, "Value out of range: {}", detail),
            DateError::ParsingError(detail) => return write!(f, "Error parsing value: {}", detail),
            DateError::IncorrectUnit(unit) => {
                return write!(f, "Unrecognized unit of measurement: {}", unit)
            }
        };
        write!(f, "{}", msg)
    }
}

impl Error for DateError {}

/// Global variable for the time zone; by default, if not set, it will be Local.
static TZ_OPTION: OnceCell<TimeZoneOption> = OnceCell::new();

/* ============================== Date Utility Functions ============================== */

/// Sets the global time zone for the library.
///
/// If not called, the default will be 'TimeZoneOption::Local'.
///
/// # Example
///
///
/// use date_filter_search::{set_timezone_option, TimeZoneOption};
///
/// set_timezone_option(TimeZoneOption::Utc);
///
pub fn set_timezone_option(option: TimeZoneOption) {
    let _ = TZ_OPTION.set(option);
}

/// Returns the currently configured time zone.
///
/// If no time zone has been set via 'set_timezone_option',
/// it returns 'TimeZoneOption::Local'.
///
fn get_timezone_option() -> TimeZoneOption {
    *TZ_OPTION.get().unwrap_or(&TimeZoneOption::Local)
}

/// Returns the current date and time using the configured time zone.
///
/// By default, it uses the local time zone, but if the user sets
/// 'TimeZoneOption::Utc' via 'set_timezone_option', UTC will be used.
///
/// # Example
///
///
/// use date_filter_search::{get_current_date, set_timezone_option, TimeZoneOption};
///
/// // Uses the default (Local)
/// let local_date = get_current_date();
///
/// // Set the time zone to UTC and get the current date
/// set_timezone_option(TimeZoneOption::Utc);
/// let utc_date = get_current_date();
///
pub fn get_current_date() -> DateTime {
    let tz_option = get_timezone_option();
    let now = match tz_option {
        TimeZoneOption::Local => Local::now().naive_local(),
        TimeZoneOption::Utc => Utc::now().naive_utc(),
    };
    let dt = DateTime {
        year: now.year() as u16,
        month: now.month() as u8,
        day: now.day() as u8,
        hour: now.hour() as u8,
        minute: now.minute() as u8,
        second: now.second() as u8,
    };
    dt
}

/// Returns the minimum date (start of epoch) as 'DateTime'.
fn get_start_date() -> DateTime {
    DateTime {
        year: YEAR_START,
        month: 1,
        day: 1,
        hour: 0,
        minute: 0,
        second: 0,
    }
}

/// Returns the maximum date as 'DateTime'.
fn get_end_date() -> DateTime {
    DateTime {
        year: YEAR_END,
        month: 12,
        day: 31,
        hour: 23,
        minute: 59,
        second: 59,
    }
}

/// Checks if a year is a leap year.
///
/// # Parameters
///
/// - 'year': The year to check.
///
/// # Returns
///
/// 'true' if the year is a leap year, 'false' otherwise.
///
fn leap_year(year: u16) -> bool {
    ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)
}

/// Calculates the number of days in a given month, considering leap years.
///
/// # Parameters
///
/// - 'month': The month (1-12).
/// - 'year': The year.
///
/// # Returns
///
/// The number of days in the month.
///
fn days_of_the_month(month: u8, year: u16) -> u8 {
    match month {
        4 | 6 | 9 | 11 => 30,
        2 => {
            if leap_year(year) {
                29
            } else {
                28
            }
        }
        _ => 31,
    }
}

/// Converts a number of seconds (since 'YEAR_START') into a 'DateTime' structure.
///
/// # Parameters
///
/// - 'seconds': The seconds to convert.
///
/// # Returns
///
/// The corresponding date as 'DateTime'.
///
pub fn seconds_to_date(mut seconds: u64) -> DateTime {
    let mut dt = get_start_date();

    loop {
        let secs_in_year: u64 = if leap_year(dt.year) {
            366 * 86400
        } else {
            365 * 86400
        };

        if seconds < secs_in_year {
            break;
        }

        seconds -= secs_in_year;
        dt.year += 1;
    }
    loop {
        let secs_in_month: u64 = (days_of_the_month(dt.month, dt.year) as u64) * 86400;

        if seconds < secs_in_month {
            break;
        }
        seconds -= secs_in_month;
        dt.month += 1;
    }
    dt.day = ((seconds / 86400) + 1) as u8;
    seconds %= 86400;
    dt.hour = (seconds / 3600) as u8;
    seconds %= 3600;
    dt.minute = (seconds / 60) as u8;
    dt.second = (seconds % 60) as u8;
    dt
}

/// Converts a 'DateTime' structure into the number of seconds (since 'YEAR_START').
///
/// # Parameters
///
/// - 'dt': The date to convert.
///
/// # Returns
///
/// The corresponding number of seconds.
///
pub fn date_to_seconds(dt: DateTime) -> u64 {
    let mut seconds: u64 = 0;

    for y in YEAR_START..dt.year {
        seconds += if leap_year(y) {
            366 * 86400
        } else {
            365 * 86400
        };
    }

    for m in 1..dt.month {
        seconds += (days_of_the_month(m, dt.year) as u64) * 86400;
    }

    seconds += ((dt.day - 1) as u64) * 86400;
    seconds += (dt.hour as u64) * 3600;
    seconds += (dt.minute as u64) * 60;
    seconds += dt.second as u64;
    seconds
}

/* ============================== Functions to get "calendar" boundaries ============================== */

/// Returns the date with the time set to the beginning of the day (00:00:00).
fn get_start_of_day(mut dt: DateTime) -> DateTime {
    dt.hour = 0;
    dt.minute = 0;
    dt.second = 0;
    dt
}

/// Returns the date with the day set to the first of the month, with time set to 00:00:00.
fn get_start_of_month(mut dt: DateTime) -> DateTime {
    dt.day = 1;
    dt.hour = 0;
    dt.minute = 0;
    dt.second = 0;
    dt
}

/// Returns the date set to the first day of the year, with time set to 00:00:00.
fn get_start_of_year(mut dt: DateTime) -> DateTime {
    dt.month = 1;
    dt.day = 1;
    dt.hour = 0;
    dt.minute = 0;
    dt.second = 0;
    dt
}

/* ============================== Functions to "subtract" time ============================== */

/// Subtracts a given number of months from the timestamp (in seconds).
///
/// # Parameters
///
/// - 'now': The current timestamp in seconds.
/// - 'months': The number of months to subtract.
///
/// # Returns
///
/// The new timestamp in seconds.
///
fn subtract_months(now: u64, months: u64) -> u64 {
    let mut dt = seconds_to_date(now);
    let mut total_months = dt.year as u64 * 12 + dt.month as u64 - 1;
    total_months = total_months.saturating_sub(months);
    dt.year = (total_months / 12) as u16;
    dt.month = ((total_months % 12) + 1) as u8;
    let dim = days_of_the_month(dt.month, dt.year);
    if dt.day > dim {
        dt.day = dim;
    }
    date_to_seconds(dt)
}

/// Subtracts a given number of years from the timestamp (in seconds).
///
/// # Parameters
///
/// - 'now': The current timestamp in seconds.
/// - 'years': The number of years to subtract.
///
/// # Returns
///
/// The new timestamp in seconds.
///
fn subtract_years(now: u64, years: u64) -> u64 {
    let mut dt = seconds_to_date(now);
    dt.year = dt.year.saturating_sub(years as u16);
    let dim = days_of_the_month(dt.month, dt.year);
    if dt.day > dim {
        dt.day = dim;
    }
    date_to_seconds(dt)
}

/// Subtracts a given number of days from the timestamp (in seconds).
///
/// # Parameters
///
/// - 'now': The current timestamp in seconds.
/// - 'days': The number of days to subtract.
///
/// # Returns
///
/// The new timestamp in seconds.
///
fn subtract_days(now: u64, days: u64) -> u64 {
    now.saturating_sub(days * 86400)
}

/* ============================== Search Function ============================== */

/// Checks if a target timestamp is between 'lower_bound' and 'upper_bound' (inclusive).
///
/// # Parameters
///
/// - 'target': The timestamp to check.
/// - 'lower_bound': The lower bound.
/// - 'upper_bound': The upper bound.
///
/// # Returns
///
/// 'true' if 'target' is within the range, 'false' otherwise.
///
pub fn search_generic(target: u64, lower_bound: u64, upper_bound: u64) -> bool {
    target >= lower_bound && target <= upper_bound
}

/* ============================== Validation function ============================== */

/// Validates an input string and converts it into a 'DateTime' structure.
///
/// If 'default' is 'true', missing values are filled with the minimum value; otherwise, with the maximum value.
///
/// # Parameters
///
/// - 'input': The string containing the date.
/// - 'default': If 'true', missing fields use the minimum value; if 'false', the maximum value.
///
/// # Returns
///
/// A 'Result' containing a valid 'DateTime' or a 'DateError'.
///
pub fn validate_datetime(input: &str, default: bool) -> Result<DateTime, DateError> {
    let re = Regex::new(
        r"^(\d{4})(?:[\-_:;.,/\\|\s]+(\d{1,2}))?(?:[\-_:;.,/\\|\s]+(\d{1,2}))?(?:[\-_:;.,/\\|\s]+(\d{1,2}))?(?:[\-_:;.,/\\|\s]+(\d{1,2}))?(?:[\-_:;.,/\\|\s]+(\d{1,2}))?$",
    )
    .map_err(|_| DateError::InvalidRegex)?;

    let caps = re.captures(input).ok_or(DateError::InvalidDateFormat)?;

    let mut dt = if default {
        get_start_date()
    } else {
        get_end_date()
    };

    if let Some(y) = caps.get(1) {
        dt.year = y
            .as_str()
            .parse()
            .map_err(|e| DateError::ParsingError(format!("Year: {}", e)))?;
        if dt.year < YEAR_START || dt.year > YEAR_END {
            return Err(DateError::OutOfRange(format!(
                "The year must be between {} and {}.",
                YEAR_START, YEAR_END
            )));
        }
    }

    if let Some(m) = caps.get(2) {
        dt.month = m
            .as_str()
            .parse()
            .map_err(|e| DateError::ParsingError(format!("Month: {}", e)))?;
        if dt.month < 1 || dt.month > 12 {
            return Err(DateError::OutOfRange(
                "The month must be between 1 and 12.".to_string(),
            ));
        }
    }

    if let Some(d) = caps.get(3) {
        dt.day = d
            .as_str()
            .parse()
            .map_err(|e| DateError::ParsingError(format!("Day: {}", e)))?;
        let max_day = days_of_the_month(dt.month, dt.year);
        if dt.day < 1 || dt.day > max_day {
            return Err(DateError::OutOfRange(format!(
                "The day must be between 1 and {} for the month {}.",
                max_day, dt.month
            )));
        }
    }

    if let Some(h) = caps.get(4) {
        dt.hour = h
            .as_str()
            .parse()
            .map_err(|e| DateError::ParsingError(format!("Hour: {}", e)))?;
        if dt.hour > 23 {
            return Err(DateError::OutOfRange(
                "The hour must be between 0 and 23.".to_string(),
            ));
        }
    }

    if let Some(mi) = caps.get(5) {
        dt.minute = mi
            .as_str()
            .parse()
            .map_err(|e| DateError::ParsingError(format!("Minute: {}", e)))?;
        if dt.minute > 59 {
            return Err(DateError::OutOfRange(
                "The minutes must be between 0 and 59.".to_string(),
            ));
        }
    }

    if let Some(s) = caps.get(6) {
        dt.second = s
            .as_str()
            .parse()
            .map_err(|e| DateError::ParsingError(format!("Seconds: {}", e)))?;
        if dt.second > 59 {
            return Err(DateError::OutOfRange(
                "The seconds must be between 0 and 59.".to_string(),
            ));
        }
    }

    Ok(dt)
}

/* ============================== Parsing user input ============================== */

/// Parses an input string interpreting it as an absolute date range.
///
/// If the input contains the delimiter defined in 'UNIT_DELIMITER', it is considered a range:
/// - The first part is parsed with default (minimum) values for missing fields.
/// - The second part is parsed with default (maximum) values for missing fields.
/// Otherwise, it is interpreted as a single date and both the start and end are derived from it.
///
/// # Parameters
///
/// - 'input': The string to parse, e.g., "2021-03 to 2021-06" or "2023-04-05 10:20:30" or "2024".
///
/// # Returns
///
/// A 'Result' containing a tuple '(start, end)' in seconds or a 'DateError'.
///
fn parsing_search_absolute(input: &str) -> Result<(u64, u64), DateError> {
    let parts: Vec<&str> = input.splitn(2, UNIT_DELIMITER).map(|s| s.trim()).collect();
    let start_dt = validate_datetime(parts[0], true)?;
    let start = date_to_seconds(start_dt);

    let end = if parts.len() > 1 {
        let end_dt = validate_datetime(parts[1], false)?;
        date_to_seconds(end_dt)
    } else {
        let end_dt = validate_datetime(parts[0], false)?;
        date_to_seconds(end_dt)
    };

    Ok((start, end))
}

/// Parses an input string interpreting it as a relative date range.
///
/// The input must be in the format '<value><unit>', where:
/// - '<value>' is a numeric value,
/// - '<unit>' is one of the allowed units: 's' (seconds), 'm' (minutes), 'h' (hours),
/// 'D' (days), 'M' (months), or 'Y' (years).
///
/// The function calculates a start time by subtracting the given value (converted according to the unit)
/// from the current date (obtained via 'get_current_date()'), while the end time is set to the current date.
///
/// # Parameters
///
/// - 'input': The string to parse, e.g., "10m" for 10 minutes relative to now.
///
/// # Returns
///
/// A 'Result' containing a tuple '(start, end)' in seconds or a 'DateError'.
///
fn parsing_search_relative(input: &str) -> Result<(u64, u64), DateError> {
    let re = Regex::new(r"^(\d+)\s*([A-Za-z])$").map_err(|_| DateError::InvalidRegex)?;
    let caps = re.captures(input).ok_or(DateError::InvalidDateFormat)?;

    let value: u64 = caps
        .get(1)
        .unwrap()
        .as_str()
        .parse()
        .map_err(|e| DateError::ParsingError(format!("Value: {}", e)))?;
    let unit = caps.get(2).unwrap().as_str();

    let now_dt = get_current_date();
    let start: u64 = match unit {
        UNIT_SECONDS => date_to_seconds(get_current_date()).saturating_sub(value),
        UNIT_MINUTES => date_to_seconds(get_current_date()).saturating_sub(value * 60),
        UNIT_HOURS => date_to_seconds(get_current_date()).saturating_sub(value * 3600),
        UNIT_DAYS => {
            let start_dt = get_start_of_day(now_dt);
            if value > 1 {
                let start_ts = subtract_days(date_to_seconds(start_dt), value - 1);
                date_to_seconds(get_start_of_day(seconds_to_date(start_ts)))
            } else {
                date_to_seconds(start_dt)
            }
        }
        UNIT_MONTHS => {
            let start_dt = get_start_of_month(now_dt);
            if value > 1 {
                let start_ts = subtract_months(date_to_seconds(start_dt), value - 1);
                date_to_seconds(get_start_of_month(seconds_to_date(start_ts)))
            } else {
                date_to_seconds(start_dt)
            }
        }
        UNIT_YEARS => {
            let start_dt = get_start_of_year(now_dt);
            if value > 1 {
                let start_ts = subtract_years(date_to_seconds(start_dt), value - 1);
                date_to_seconds(get_start_of_year(seconds_to_date(start_ts)))
            } else {
                date_to_seconds(start_dt)
            }
        }
        other => return Err(DateError::IncorrectUnit(other.to_string())),
    };

    let global_start = date_to_seconds(get_start_date());
    if start < global_start {
        return Err(DateError::OutOfRange(
            "The requested period is earlier than the minimum allowed date.".to_string(),
        ));
    }
    let end = date_to_seconds(get_current_date());
    Ok((start, end))
}

/// Parses the input string and determines whether to interpret it as a relative or absolute date range.
///
/// # Parameters
///
/// - 'input': The string to parse.
///
/// # Returns
///
/// A 'Result' containing a tuple '(start, end)' in seconds, or a 'DateError'.
///
pub fn parsing_search(input: &str) -> Result<(u64, u64), DateError> {
    if input.trim().is_empty() {
        return Err(DateError::EmptyInput);
    }

    let pat = Regex::new(r"^(\d+)\s*([A-Za-z])$").unwrap();
    let (start, end);
    if let Some(_) = pat.captures(input) {
        (start, end) = parsing_search_relative(input)?;
    } else {
        (start, end) = parsing_search_absolute(input)?;
    }
    Ok((start, end))
}

/* ============================== Converting a string to Date_Time  ============================== */

/// Converts a string representing a date into the number of seconds since the epoch ('YEAR_START').
///
/// # Parameters
///
/// - 'input': The string containing the date.
///
/// # Returns
///
/// A 'Result' containing the number of seconds or a 'DateError' if the input is invalid.
///
pub fn string_to_date_seconds(input: &str) -> Result<u64, DateError> {
    if input.trim().is_empty() {
        return Err(DateError::EmptyInput);
    }
    let dt = validate_datetime(input, true)?;
    Ok(date_to_seconds(dt))
}