Skip to content

Commit c8332fd

Browse files
authored
Add helper for parsing Unix time stamps from str (Azure#2167)
1 parent 86babf1 commit c8332fd

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

sdk/typespec/typespec_client_core/src/date/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ pub mod iso8601;
2121
pub mod rfc7231;
2222
pub mod unix_time;
2323

24+
pub use unix_time::parse_unix_time;
25+
2426
/// RFC 3339: Date and Time on the Internet: Timestamps.
2527
///
2628
/// <https://www.rfc-editor.org/rfc/rfc3339>

sdk/typespec/typespec_client_core/src/date/unix_time.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
//! Unix timestamp serde helpers.
55
use serde::{de, Deserialize, Deserializer, Serializer};
6+
use std::str::FromStr;
67
use time::{OffsetDateTime, UtcOffset};
78

89
/// Deserialize a Unix timestamp into an [`OffsetDateTime`].
@@ -22,6 +23,13 @@ where
2223
serializer.serialize_i64(date.to_offset(UtcOffset::UTC).unix_timestamp())
2324
}
2425

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+
2533
pub mod option {
2634
use serde::{Deserialize, Deserializer, Serializer};
2735
use time::{OffsetDateTime, UtcOffset};
@@ -51,6 +59,7 @@ pub mod option {
5159

5260
#[cfg(test)]
5361
mod tests {
62+
use crate::date::parse_unix_time;
5463
use crate::json::{from_json, to_json};
5564
use serde::{Deserialize, Serialize};
5665
use time::macros::datetime;
@@ -131,4 +140,15 @@ mod tests {
131140
);
132141
Ok(())
133142
}
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+
}
134154
}

0 commit comments

Comments
 (0)