dateless/event/period/
start_end.rs1use chrono::{Date, DateTime, Datelike, Duration, NaiveDate, NaiveTime, Utc};
2
3#[cfg(feature = "serde_support")]
4use chrono::serde::ts_seconds;
5
6#[cfg(feature = "serde_support")]
7use serde::{Deserialize, Serialize};
8
9use super::Period;
10
11#[derive(Debug, Clone)]
12#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
13pub struct StartEnd(
14 #[cfg_attr(feature = "serde_support", serde(with = "ts_seconds"))] pub DateTime<Utc>,
15 #[cfg_attr(feature = "serde_support", serde(with = "ts_seconds"))] pub DateTime<Utc>,
16);
17
18#[cfg_attr(feature = "serde_support", typetag::serde)]
19impl Period for StartEnd {
20 fn contains(&self, date: Date<Utc>) -> bool {
21 {
22 let date = date.and_time(NaiveTime::from_hms(0, 0, 0)).unwrap();
23 if !((self.0 - date).num_milliseconds() >= 0 || (self.1 - date).num_milliseconds() > 0)
24 {
25 return false;
26 }
27 }
28 let date = (date + Duration::days(1))
29 .and_time(Utc::now().time())
30 .unwrap();
31 (self.0 - date).num_milliseconds() < 0
32 }
33
34 fn get_date_time_start(&self) -> DateTime<Utc> {
35 self.0.clone()
36 }
37
38 fn starts_before(&self, date: Date<Utc>) -> bool {
39 let date = date.and_time(Utc::now().time()).unwrap();
40 (self.0 - date).num_milliseconds() < 0
41 }
42
43 fn with_new_start(&self, date: Date<Utc>) -> Box<dyn Period> {
44 let total_duration = self.1 - self.0;
45 let time_at_start = self.0.time();
46
47 let date = date.and_time(time_at_start).unwrap();
48
49 Box::new(Self(date, date + total_duration))
50 }
51
52 fn as_weekdays(&self) -> (u32, u32) {
53 (
54 self.0.date().weekday().number_from_monday(),
55 self.1.date().weekday().number_from_monday(),
56 )
57 }
58
59 fn as_days_of_month(&self) -> (u32, u32) {
60 (self.0.day(), self.1.day())
61 }
62
63 fn as_months(&self) -> (u32, u32) {
64 (self.0.date().day(), self.1.date().day())
65 }
66
67 fn with_new_month(&self, month: u32) -> Date<Utc> {
68 Date::from_utc(NaiveDate::from_ymd(self.0.year(), month, self.0.day()), Utc)
69 }
70
71 fn cloned(&self) -> Box<dyn Period> {
72 Box::new(self.clone())
73 }
74}