Skip to main content

sea_orm/value/
with_time.rs

1use super::impl_timestamp;
2use crate as sea_orm;
3use crate::{DbErr, TryGetError, prelude::TimeDateTimeWithTimeZone};
4use std::ops::{Deref, DerefMut};
5
6/// An `OffsetDateTime` stored as a Unix timestamp (seconds) `i64` in the database.
7#[derive(derive_more::Debug, Copy, Clone, PartialEq, Eq, Hash)]
8#[debug("{_0:?}")]
9pub struct TimeUnixTimestamp(pub TimeDateTimeWithTimeZone);
10
11/// An `OffsetDateTime` stored as a Unix timestamp in milliseconds (`i64`) in the database.
12#[derive(derive_more::Debug, Copy, Clone, PartialEq, Eq, Hash)]
13#[debug("{_0:?}")]
14pub struct TimeUnixTimestampMillis(pub TimeDateTimeWithTimeZone);
15
16impl_timestamp!(
17    TimeUnixTimestamp,
18    TimeDateTimeWithTimeZone,
19    from_timestamp,
20    to_timestamp
21);
22super::impl_serde_with_i64!(TimeUnixTimestamp, from_timestamp, to_timestamp);
23
24impl_timestamp!(
25    TimeUnixTimestampMillis,
26    TimeDateTimeWithTimeZone,
27    from_timestamp_millis,
28    to_timestamp_millis
29);
30super::impl_serde_with_i64!(
31    TimeUnixTimestampMillis,
32    from_timestamp_millis,
33    to_timestamp_millis
34);
35
36fn from_timestamp(ts: i64) -> Option<TimeUnixTimestamp> {
37    TimeDateTimeWithTimeZone::from_unix_timestamp(ts)
38        .ok()
39        .map(TimeUnixTimestamp)
40}
41
42fn to_timestamp(ts: TimeUnixTimestamp) -> i64 {
43    ts.0.unix_timestamp()
44}
45
46fn from_timestamp_millis(ts: i64) -> Option<TimeUnixTimestampMillis> {
47    TimeDateTimeWithTimeZone::from_unix_timestamp_nanos(ts as i128 * 1_000_000)
48        .ok()
49        .map(TimeUnixTimestampMillis)
50}
51
52fn to_timestamp_millis(ts: TimeUnixTimestampMillis) -> i64 {
53    (ts.0.unix_timestamp_nanos() / 1_000_000) as i64
54}