Expand description
Flexible timestamp serde: deserializes from Unix epoch (integer or float) or ISO 8601 / RFC 3339 string; always serializes as an RFC 3339 string.
Requires the chrono feature.
§Wire formats accepted on deserialization
| Input | Interpretation |
|---|---|
1_700_000_000 (i64) | Unix epoch seconds |
1_700_000_000.5 (f64) | Unix epoch seconds + sub-second |
"2023-11-14T22:13:20Z" | RFC 3339 / ISO 8601 string |
§Examples
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Event {
#[serde(with = "api_bones::serde::timestamp")]
occurred_at: DateTime<Utc>,
}
// Deserialize from epoch integer
let from_epoch: Event = serde_json::from_str(r#"{"occurred_at":0}"#).unwrap();
assert_eq!(from_epoch.occurred_at, DateTime::<Utc>::from_timestamp(0, 0).unwrap());
// Deserialize from RFC 3339 string
let from_str: Event =
serde_json::from_str(r#"{"occurred_at":"1970-01-01T00:00:00+00:00"}"#).unwrap();
assert_eq!(from_str.occurred_at, from_epoch.occurred_at);
// Always serializes as RFC 3339
let json = serde_json::to_string(&from_epoch).unwrap();
assert_eq!(json, r#"{"occurred_at":"1970-01-01T00:00:00+00:00"}"#);§Feature gating
This module is re-exported only when the chrono feature is enabled
(see serde/mod.rs). The serde feature gate on the parent serde
module is a necessary but not sufficient condition — chrono must
also be active for this module to be available. The explicit
#[cfg(feature = "chrono")] in mod.rs is the authoritative gate;
serde is required transitively because DateTime<Utc> serialization
depends on it.
Functions§
- deserialize
- Deserialize a
DateTime<Utc>from a Unix epoch integer, float, or RFC 3339 string. - serialize
- Serialize a
DateTime<Utc>as an RFC 3339 string.