time::serde

Macro format_description

source
format_description!() { /* proc-macro */ }
Expand description

Generate a custom serializer and deserializer from a format string or an existing format.

The syntax accepted by this macro is the same as format_description::parse(), which can be found in the book.

§Usage

Invoked as serde::format_description!(mod_name, Date, FORMAT) where FORMAT is either a "<format string>" or something that implements Formattable and Parsable. This puts a module named mod_name in the current scope that can be used to format Date structs. A submodule (mod_name::option) is also generated for Option<Date>. Both modules are only visible in the current scope.

The returned Option will contain a deserialized value if present and None if the field is present but the value is null (or the equivalent in other formats). To return None when the field is not present, you should use #[serde(default)] on the field.

§Examples

Using a format string:

use ::serde::{Serialize, Deserialize};
use time::serde;

// Makes a module `mod my_format { ... }`.
serde::format_description!(my_format, OffsetDateTime, "hour=[hour], minute=[minute]");

#[derive(Serialize, Deserialize)]
struct SerializesWithCustom {
    #[serde(with = "my_format")]
    dt: OffsetDateTime,
    #[serde(with = "my_format::option")]
    maybe_dt: Option<OffsetDateTime>,
}

Define the format separately to be used in multiple places:

use ::serde::{Serialize, Deserialize};
use time::serde;
use time::format_description::BorrowedFormatItem;

const DATE_TIME_FORMAT: &[BorrowedFormatItem<'_>] = time::macros::format_description!(
    "hour=[hour], minute=[minute]"
);

// Makes a module `mod my_format { ... }`.
serde::format_description!(my_format, OffsetDateTime, DATE_TIME_FORMAT);

#[derive(Serialize, Deserialize)]
struct SerializesWithCustom {
    #[serde(with = "my_format")]
    dt: OffsetDateTime,
    #[serde(with = "my_format::option")]
    maybe_dt: Option<OffsetDateTime>,
}

fn main() {
    let str_ts = OffsetDateTime::now_utc().format(DATE_TIME_FORMAT).unwrap();
}

Customize the configuration of ISO 8601 formatting/parsing:

use ::serde::{Serialize, Deserialize};
use time::serde;
use time::format_description::well_known::{iso8601, Iso8601};

const CONFIG: iso8601::EncodedConfig = iso8601::Config::DEFAULT
    .set_year_is_six_digits(false)
    .encode();
const FORMAT: Iso8601<CONFIG> = Iso8601::<CONFIG>;

// Makes a module `mod my_format { ... }`.
serde::format_description!(my_format, OffsetDateTime, FORMAT);

#[derive(Serialize, Deserialize)]
struct SerializesWithCustom {
    #[serde(with = "my_format")]
    dt: OffsetDateTime,
    #[serde(with = "my_format::option")]
    maybe_dt: Option<OffsetDateTime>,
}