| 1 | use super::timezone::Tz; |
| 2 | use chrono::{Datelike, Duration, NaiveTime, Timelike}; |
| 3 | |
| 4 | pub(crate) fn duration_from_midnight(time: NaiveTime) -> Duration { |
| 5 | Duration::hours(i64::from(time.hour())) |
| 6 | + Duration::minutes(i64::from(time.minute())) |
| 7 | + Duration::seconds(i64::from(time.second())) |
| 8 | } |
| 9 | |
| 10 | pub(crate) fn get_month(dt: &chrono::DateTime<Tz>) -> u8 { |
| 11 | u8::try_from(dt.month()).expect("month is between 1-12 which is covered by u8") |
| 12 | } |
| 13 | |
| 14 | pub(crate) fn get_day(dt: &chrono::DateTime<Tz>) -> i8 { |
| 15 | i8::try_from(dt.day()).expect("day is between 1-31 which is covered by i8") |
| 16 | } |
| 17 | |
| 18 | pub(crate) fn get_hour(dt: &chrono::DateTime<Tz>) -> u8 { |
| 19 | u8::try_from(dt.hour()).expect("hour is between 0-23 which is covered by u8") |
| 20 | } |
| 21 | |
| 22 | pub(crate) fn get_minute(dt: &chrono::DateTime<Tz>) -> u8 { |
| 23 | u8::try_from(dt.minute()).expect("minute is between 0-59 which is covered by u8") |
| 24 | } |
| 25 | |
| 26 | pub(crate) fn get_second(dt: &chrono::DateTime<Tz>) -> u8 { |
| 27 | u8::try_from(dt.second()).expect("second is between 0-59 which is covered by u8") |
| 28 | } |
| 29 | |
| 30 | /// Generates an iCalendar date-time string format with the prefix symbols. |
| 31 | /// Like: `:19970714T173000Z` or `;TZID=America/New_York:19970714T133000` |
| 32 | /// ref: <https://tools.ietf.org/html/rfc5545#section-3.3.5> |
| 33 | pub(crate) fn datetime_to_ical_format(dt: &chrono::DateTime<Tz>) -> String { |
| 34 | let mut tz_prefix = String::new(); |
| 35 | let mut tz_postfix = String::new(); |
| 36 | let tz = dt.timezone(); |
| 37 | match tz { |
| 38 | Tz::Local(_) => {} |
| 39 | Tz::Tz(tz) => match tz { |
| 40 | chrono_tz::UTC => { |
| 41 | tz_postfix = "Z".to_string(); |
| 42 | } |
| 43 | tz => { |
| 44 | tz_prefix = format!(";TZID={}", tz.name()); |
| 45 | } |
| 46 | }, |
| 47 | } |
| 48 | |
| 49 | let dt = dt.format("%Y%m%dT%H%M%S"); |
| 50 | format!("{}:{}{}", tz_prefix, dt, tz_postfix) |
| 51 | } |