summaryrefslogtreecommitdiff
path: root/src/serde.rs
blob: 13ef8bc0f768409df3adb3afbc731d3074ad5d43 (plain)
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
use chrono::{DateTime, NaiveDateTime, Utc};
use serde::{Deserialize, Deserializer};

pub fn naive_read_unixtime<'de, D>(d: D) -> Result<DateTime<Utc>, D::Error>
where
  D: Deserializer<'de>
{
  let ts = <i64>::deserialize(d)?;
  Ok(DateTime::<Utc>::from_utc(
    NaiveDateTime::from_timestamp(ts, 0),
    Utc
  ))
}

pub fn option_naive_read_unixtime<'de, D>(
  d: D
) -> Result<Option<DateTime<Utc>>, D::Error>
where
  D: Deserializer<'de>
{
  match <i64>::deserialize(d) {
    Ok(ts) => Ok(Some(DateTime::<Utc>::from_utc(
      NaiveDateTime::from_timestamp(ts, 0),
      Utc
    ))),
    Err(_) => Ok(None)
  }
}

pub fn option_naive_read_unixtime_db<'de, D>(
  d: D
) -> Result<Option<DateTime<Utc>>, D::Error>
where
  D: Deserializer<'de>
{
  match <i64>::deserialize(d) {
    Ok(ts) => Ok(Some(DateTime::<Utc>::from_utc(
      NaiveDateTime::from_timestamp(ts / 1000, 0),
      Utc
    ))),
    Err(_) => Ok(None)
  }
}