haystack_types/
h_datetime.rs

1use std::str::FromStr;
2use core::fmt::Display;
3use num::Float;
4use crate::{HType, HVal, NumTrait};
5use std::fmt::{self,Write};
6
7use chrono::{NaiveDateTime as DT, NaiveDate};
8use chrono::{Datelike,Timelike};
9
10#[derive(Debug,PartialEq)]
11pub struct HDateTime {
12    inner: DT,
13    // TODO: Implement timezones to work with `chrono_tz`
14    // tz: (chrono_tz::Tz, HOffset)
15    tz: (String, HOffset)
16}
17
18#[derive(Debug,PartialEq)]
19pub enum HOffset {
20    Fixed(chrono::FixedOffset),
21    Variable(chrono::Duration),
22    Utc
23}
24
25pub type DateTime = HDateTime;
26
27const THIS_TYPE: HType = HType::DateTime;
28
29impl HDateTime {
30    pub fn new(year: i32, month: u32, day: u32, hour: u32, min: u32, sec: u32, nano: u32, tz: (String /* chrono_tz::Tz*/, HOffset)) -> Self {
31        let inner = NaiveDate::from_ymd(year, month, day)
32            .and_hms_nano(hour, min, sec, nano);
33
34        Self { inner, tz }
35    }
36
37    pub fn val(&self) -> DT {
38        self.inner
39    }
40}
41
42impl <'a,T: NumTrait + 'a>HVal<'a,T> for HDateTime {
43    fn to_zinc(&self, buf: &mut String) -> fmt::Result {
44        write!(buf,"{:0>4}-{:0>2}-{:0>2}T",self.inner.year(),self.inner.month(),self.inner.day())?;
45        write!(buf,"{:0>2}:{:0>2}:{:0>2}.{}",self.inner.hour(),self.inner.minute(),self.inner.second(),
46        self.inner.nanosecond())
47    }
48    fn to_json(&self, buf: &mut String) -> fmt::Result {
49        write!(buf,"t:")?;
50        let it: &dyn HVal<T> = self;
51        it.to_zinc(buf)
52    }
53    fn haystack_type(&self) -> HType { THIS_TYPE }
54
55    set_trait_eq_method!(get_datetime_val,'a,T);
56    set_get_method!(get_datetime_val, HDateTime);
57}