Skip to main content

rust_dynamic/
timestamp.rs

1use unix_ts::Timestamp;
2use chrono::{DateTime, Utc};
3use crate::value::{Value, timestamp_ns};
4use crate::types::*;
5
6impl Value {
7    pub fn get_timestamp(&self) -> f64 {
8        self.stamp
9    }
10    pub fn get_timestamp_as_datetime(&self) -> DateTime<Utc> {
11        match self.data {
12            Val::Time(u_val) => {
13                let ts = Timestamp::from_nanos(u_val as i128);
14                return DateTime::from_timestamp_nanos(ts.at_precision(9) as i64);
15            }
16            _ => {
17                return Utc::now();
18            }
19        }
20    }
21    pub fn timestamp_diff(&self, other: Self) -> f64 {
22        self.stamp - other.get_timestamp()
23    }
24    pub fn elapsed(&self) -> Result<u128, Box<dyn std::error::Error>> {
25        if self.dt != TIME {
26            return Err("Incorrect type for the method, TIME required".into());
27        }
28        match self.data {
29            Val::Time(u_val) => {
30                return Result::Ok(timestamp_ns() - u_val);
31            }
32            _ => Err("Value of type TIME is corrupted".into()),
33        }
34    }
35    pub fn elapsed_value(&self) -> Result<Self, Box<dyn std::error::Error>> {
36        if self.dt != TIME {
37            return Err("Incorrect type for the method, TIME required".into());
38        }
39        match self.data {
40            Val::Time(u_val) => {
41                return Result::Ok(Value::from_timestamp(timestamp_ns() - u_val));
42            }
43            _ => Err("Value of type TIME is corrupted".into()),
44        }
45    }
46    pub fn get_time_as_datetime(&self) -> Result<DateTime<Utc>, Box<dyn std::error::Error>> {
47        if self.dt != TIME {
48            return Err("Value must be of type TIME".into());
49        }
50        match self.data {
51            Val::Time(u_val) => {
52                let ts = Timestamp::from_nanos(u_val as i128);
53                return Ok(DateTime::from_timestamp_nanos(ts.at_precision(9) as i64));
54            }
55            _ => Err("Value of type TIME is corrupted".into()),
56        }
57    }
58}