tea_time/
convert.rs

1use super::timeunit::*;
2use crate::DateTime;
3
4/// The number of nanoseconds in a microsecond.
5pub const NANOS_PER_MICRO: i64 = 1000;
6/// The number of nanoseconds in a millisecond.
7pub const NANOS_PER_MILLI: i64 = 1_000_000;
8/// The number of nanoseconds in seconds.
9pub const NANOS_PER_SEC: i64 = 1_000_000_000;
10/// The number of microseconds per millisecond.
11pub const MICROS_PER_MILLI: i64 = 1000;
12/// The number of microseconds per second.
13pub const MICROS_PER_SEC: i64 = 1_000_000;
14/// The number of milliseconds per second.
15pub const MILLIS_PER_SEC: i64 = 1000;
16/// The number of seconds in a minute.
17pub const SECS_PER_MINUTE: i64 = 60;
18/// The number of seconds in an hour.
19pub const SECS_PER_HOUR: i64 = 3600;
20/// The number of (non-leap) seconds in days.
21pub const SECS_PER_DAY: i64 = 86400;
22/// The number of (non-leap) seconds in a week.
23pub const SECS_PER_WEEK: i64 = 604800;
24
25impl<U: TimeUnitTrait> DateTime<U> {
26    pub fn into_unit<T: TimeUnitTrait>(self) -> DateTime<T> {
27        if U::unit() == T::unit() {
28            unsafe { std::mem::transmute::<DateTime<U>, DateTime<T>>(self) }
29        } else {
30            use TimeUnit::*;
31            match (U::unit(), T::unit()) {
32                (Nanosecond, Microsecond) => DateTime::new(self.0 / NANOS_PER_MICRO),
33                (Nanosecond, Millisecond) => DateTime::new(self.0 / NANOS_PER_MILLI),
34                (Nanosecond, Second) => DateTime::new(self.0 / NANOS_PER_SEC),
35                (Microsecond, Millisecond) => DateTime::new(self.0 / MICROS_PER_MILLI),
36                (Microsecond, Second) => DateTime::new(self.0 / MICROS_PER_SEC),
37                (Millisecond, Second) => DateTime::new(self.0 / MILLIS_PER_SEC),
38                (Microsecond, Nanosecond) => DateTime::new(self.0 * NANOS_PER_MICRO),
39                (Millisecond, Nanosecond) => DateTime::new(self.0 * NANOS_PER_MILLI),
40                (Second, Nanosecond) => DateTime::new(self.0 * NANOS_PER_SEC),
41                (Millisecond, Microsecond) => DateTime::new(self.0 * MICROS_PER_MILLI),
42                (Second, Microsecond) => DateTime::new(self.0 * MICROS_PER_SEC),
43                (Second, Millisecond) => DateTime::new(self.0 * MILLIS_PER_SEC),
44                // currently unit should only in [Nanosecond, Microsecond, Millisecond, Second]
45                (u1, u2) => unimplemented!("convert from {:?} to {:?} is not implemented", u1, u2),
46            }
47        }
48    }
49}