|
3 | 3 |
|
4 | 4 | //! Unix timestamp serde helpers. |
5 | 5 | use serde::{de, Deserialize, Deserializer, Serializer}; |
| 6 | +use std::str::FromStr; |
6 | 7 | use time::{OffsetDateTime, UtcOffset}; |
7 | 8 |
|
8 | 9 | /// Deserialize a Unix timestamp into an [`OffsetDateTime`]. |
|
22 | 23 | serializer.serialize_i64(date.to_offset(UtcOffset::UTC).unix_timestamp()) |
23 | 24 | } |
24 | 25 |
|
| 26 | +/// Parses the provided Unix time-stamp str into an OffsetDateTime. |
| 27 | +pub fn parse_unix_time(s: &str) -> crate::Result<OffsetDateTime> { |
| 28 | + let i = i64::from_str(s)?; |
| 29 | + OffsetDateTime::from_unix_timestamp(i) |
| 30 | + .map_err(|e| crate::Error::new(typespec::error::ErrorKind::DataConversion, e)) |
| 31 | +} |
| 32 | + |
25 | 33 | pub mod option { |
26 | 34 | use serde::{Deserialize, Deserializer, Serializer}; |
27 | 35 | use time::{OffsetDateTime, UtcOffset}; |
@@ -51,6 +59,7 @@ pub mod option { |
51 | 59 |
|
52 | 60 | #[cfg(test)] |
53 | 61 | mod tests { |
| 62 | + use crate::date::parse_unix_time; |
54 | 63 | use crate::json::{from_json, to_json}; |
55 | 64 | use serde::{Deserialize, Serialize}; |
56 | 65 | use time::macros::datetime; |
@@ -131,4 +140,15 @@ mod tests { |
131 | 140 | ); |
132 | 141 | Ok(()) |
133 | 142 | } |
| 143 | + |
| 144 | + #[test] |
| 145 | + fn test_parse_unix_time() -> crate::Result<()> { |
| 146 | + assert_eq!( |
| 147 | + parse_unix_time("1627904772").unwrap(), |
| 148 | + datetime!(2021-08-02 11:46:12 UTC) |
| 149 | + ); |
| 150 | + assert!(parse_unix_time("not-a-timestamp").is_err()); |
| 151 | + assert!(parse_unix_time("99999999999999").is_err()); |
| 152 | + Ok(()) |
| 153 | + } |
134 | 154 | } |
0 commit comments