1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
use std::convert::TryFrom;
use std::str::FromStr;

use chrono::{DateTime as CrDateTime, NaiveDateTime, Utc};
use tea_error::*;

use crate::*;

impl<U: TimeUnitTrait> From<i64> for DateTime<U> {
    #[inline]
    fn from(dt: i64) -> Self {
        DateTime::new(dt)
    }
}

impl<U: TimeUnitTrait> Default for DateTime<U> {
    #[inline]
    fn default() -> Self {
        DateTime::nat()
    }
}

impl<U: TimeUnitTrait> FromStr for DateTime<U>
where
    Self: From<CrDateTime<Utc>>,
{
    type Err = TError;

    #[inline]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        DateTime::parse(s, None)
    }
}

impl<U: TimeUnitTrait> From<NaiveDateTime> for DateTime<U>
where
    Self: From<CrDateTime<Utc>>,
{
    #[inline]
    fn from(dt: NaiveDateTime) -> Self {
        CrDateTime::from_naive_utc_and_offset(dt, Utc).into()
    }
}

impl TryFrom<DateTime<Second>> for CrDateTime<Utc> {
    type Error = TError;
    #[inline]
    fn try_from(dt: DateTime<Second>) -> TResult<Self> {
        CrDateTime::from_timestamp(dt.0, 0)
            .ok_or_else(|| terr!("Failed to convert DateTime<Second> to CrDateTime"))
    }
}

impl TryFrom<DateTime<Millisecond>> for CrDateTime<Utc> {
    type Error = TError;
    #[inline]
    fn try_from(dt: DateTime<Millisecond>) -> TResult<Self> {
        CrDateTime::from_timestamp_millis(dt.0)
            .ok_or_else(|| terr!("Failed to convert DateTime<Millisecond> to CrDateTime"))
    }
}

impl TryFrom<DateTime<Microsecond>> for CrDateTime<Utc> {
    type Error = TError;
    #[inline]
    fn try_from(dt: DateTime<Microsecond>) -> TResult<Self> {
        CrDateTime::from_timestamp_micros(dt.0)
            .ok_or_else(|| terr!("Failed to convert DateTime<Microsecond> to CrDateTime"))
    }
}

impl TryFrom<DateTime<Nanosecond>> for CrDateTime<Utc> {
    type Error = TError;
    #[inline]
    fn try_from(dt: DateTime<Nanosecond>) -> TResult<Self> {
        Ok(CrDateTime::from_timestamp_nanos(dt.0))
    }
}

impl From<CrDateTime<Utc>> for DateTime<Second> {
    #[inline]
    fn from(dt: CrDateTime<Utc>) -> Self {
        dt.timestamp().into()
    }
}

impl From<CrDateTime<Utc>> for DateTime<Millisecond> {
    #[inline]
    fn from(dt: CrDateTime<Utc>) -> Self {
        dt.timestamp_millis().into()
    }
}

impl From<CrDateTime<Utc>> for DateTime<Microsecond> {
    #[inline]
    fn from(dt: CrDateTime<Utc>) -> Self {
        dt.timestamp_micros().into()
    }
}

impl From<CrDateTime<Utc>> for DateTime<Nanosecond> {
    #[inline]
    fn from(dt: CrDateTime<Utc>) -> Self {
        dt.timestamp_nanos_opt()
            .expect("Failed to convert to nanosecond")
            .into()
    }
}