pub fn format(
format: impl AsRef<[u8]>,
broken_down_time: impl Into<BrokenDownTime>,
) -> Result<String, Error>Expand description
Format the given broken down time using the format string given.
See the module documentation for details on what’s supported.
This routine is like BrokenDownTime::format, but may be more
convenient to call. Also, it returns a String instead of accepting a
fmt::Write trait implementation to write to.
Note that broken_down_time can be anything that can be converted into
it. This includes, for example, Zoned, Timestamp, DateTime,
Date and Time.
§Errors
This returns an error when formatting failed. Formatting can fail either
because of an invalid format string, or if formatting requires a field in
BrokenDownTime to be set that isn’t. For example, trying to format a
DateTime with the %z specifier will fail because a DateTime has no
time zone or offset information associated with it.
§Example
This example shows how to format a Zoned into something resembling a RFC
2822 datetime:
use jiff::{civil::date, fmt::strtime, tz};
let zdt = date(2024, 7, 15).at(16, 24, 59, 0).in_tz("America/New_York")?;
let string = strtime::format("%a, %-d %b %Y %T %z", &zdt)?;
assert_eq!(string, "Mon, 15 Jul 2024 16:24:59 -0400");
Of course, one should prefer using the fmt::rfc2822
module, which contains a dedicated RFC 2822 printer.
§Example: date-like output
While the output of the Unix date command is likely locale specific,
this is what it looks like on my system:
use jiff::{civil::date, fmt::strtime, tz};
let zdt = date(2024, 7, 15).at(16, 24, 59, 0).in_tz("America/New_York")?;
let string = strtime::format("%a %b %e %I:%M:%S %p %Z %Y", &zdt)?;
assert_eq!(string, "Mon Jul 15 04:24:59 PM EDT 2024");
§Example: RFC 3339 compatible output with fractional seconds
use jiff::{civil::date, fmt::strtime, tz};
let zdt = date(2024, 7, 15)
.at(16, 24, 59, 123_456_789)
.in_tz("America/New_York")?;
let string = strtime::format("%Y-%m-%dT%H:%M:%S%.f%:z", &zdt)?;
assert_eq!(string, "2024-07-15T16:24:59.123456789-04:00");