chrono_intervals/
generator.rs

1//! Time interval generator.
2use chrono::{DateTime, Duration, FixedOffset, TimeZone, Utc};
3
4use crate::{intervals_impl::get_intervals_impl, Grouping, TimeInterval};
5
6/// Generator for time intervals.
7pub struct IntervalGenerator {
8    grouping: Grouping,
9    end_precision: Duration,
10    local_timezone: FixedOffset,
11    extend_begin: bool,
12    extend_end: bool,
13}
14
15impl IntervalGenerator {
16    pub fn new() -> Self {
17        IntervalGenerator {
18            grouping: Grouping::PerDay,
19            end_precision: Duration::milliseconds(1),
20            local_timezone: FixedOffset::west(0),
21            extend_begin: true,
22            extend_end: true,
23        }
24    }
25
26    pub fn with_grouping(mut self, grouping: Grouping) -> Self {
27        self.grouping = grouping;
28        self
29    }
30
31    pub fn with_precision(mut self, precision: Duration) -> Self {
32        self.end_precision = precision;
33        self
34    }
35
36    pub fn with_offset_west_secs(mut self, offset_west_secs: i32) -> Self {
37        self.local_timezone = FixedOffset::west(offset_west_secs);
38        self
39    }
40
41    pub fn without_extended_begin(mut self) -> Self {
42        self.extend_begin = false;
43        self
44    }
45
46    pub fn without_extended_end(mut self) -> Self {
47        self.extend_end = false;
48        self
49    }
50
51    pub fn without_extension(mut self) -> Self {
52        self.extend_begin = false;
53        self.extend_end = false;
54        self
55    }
56
57    pub fn get_intervals<T>(&self, begin: DateTime<T>, end: DateTime<T>) -> Vec<TimeInterval<Utc>>
58    where
59        T: TimeZone,
60    {
61        get_intervals_impl(
62            begin,
63            end,
64            &self.grouping,
65            self.end_precision,
66            &self.local_timezone,
67            &Utc,
68            self.extend_begin,
69            self.extend_end,
70        )
71    }
72}
73
74impl Default for IntervalGenerator {
75    fn default() -> Self {
76        IntervalGenerator::new()
77    }
78}