rustmax::jiff::fmt::serde

Module tz

Source
Expand description

Convenience routines for (de)serializing TimeZone values.

The required and optional sub-modules each provide serialization and deserialization routines. They are meant to be used with Serde’s with attribute.

§Advice

Serializing time zones is useful when you want to accept user configuration selecting a time zone to use. This might be beneficial when one cannot rely on a system’s time zone.

Note that when deserializing time zones that are IANA time zone identifiers, Jiff will automatically use the implicit global database to resolve the identifier to an actual time zone. If you do not want to use Jiff’s global time zone database for this, you’ll need to write your own Serde integration.

§Example

use jiff::tz::TimeZone;

#[derive(Debug, serde::Deserialize, serde::Serialize)]
struct Record {
    #[serde(with = "jiff::fmt::serde::tz::required")]
    tz: TimeZone,
}

let json = r#"{"tz":"America/Nuuk"}"#;
let got: Record = serde_json::from_str(&json)?;
assert_eq!(got.tz, TimeZone::get("America/Nuuk")?);
assert_eq!(serde_json::to_string(&got)?, json);

§Example: serializing an unknown TimeZone works

For example, when a time zone was created from TimeZone::system and a system configured time zone could not be found. One can artifically create this situation with TimeZone::unknown:

use jiff::tz::TimeZone;

#[derive(Debug, serde::Deserialize, serde::Serialize)]
struct Record {
    #[serde(with = "jiff::fmt::serde::tz::required")]
    tz: TimeZone,
}

let record = Record { tz: TimeZone::unknown() };
assert_eq!(
    serde_json::to_string(&record)?,
    r#"{"tz":"Etc/Unknown"}"#,
);

And it deserializes as well:

use jiff::tz::TimeZone;

#[derive(Debug, serde::Deserialize, serde::Serialize)]
struct Record {
    #[serde(with = "jiff::fmt::serde::tz::required")]
    tz: TimeZone,
}

let json = r#"{"tz":"Etc/Unknown"}"#;
let got: Record = serde_json::from_str(&json)?;
assert!(got.tz.is_unknown());

An unknown time zone is “allowed” to percolate through Jiff because it’s usually not desirable to return an error and completely fail if a system time zone could not be detected. On the other hand, by using a special Etc/Unknown identifier for this case, it still surfaces the fact that something has gone wrong.

Modules§