Parse dates
time
has can parse datetimes from strings, in any given format.
Parse a date from a string
-
Enable feature
parsing
. -
Using the common ISO 8601 format, via the
Iso8601
format description:
#![allow(unused)] fn main() { use time::format_description::well_known::Iso8601; use time::PrimitiveDateTime; let date = PrimitiveDateTime::parse("2022-01-02T11:12:13", &Iso8601::DEFAULT) .unwrap(); }
Parsing custom formats
time
supports a few common formats, that we call well-known formats. We support
arbitrary formats as well.
-
Enable feature
macros
andparsing
.macros
are used to callformat_description!
, but you can also call the equivalent function. -
Create a format and parse:
#![allow(unused)] fn main() { use time::macros::format_description; use time::Time; let my_format = format_description!("h=[hour],m=[minute],s=[second]"); let time = Time::parse("h=11,m=12,s=13", &my_format).unwrap(); }
Reference for format descriptions can be found here.
Parsing into structs with serde
For convenience, you can use Serde with time
.
-
Enable [feature
serde-well-known
][serde-well-known]. -
Create a struct and parse from a format, eg. JSON using
serde-json
:
use time::macros::format_description; use time::{OffsetDateTime, Time}; use serde::{Deserialize}; #[derive(Deserialize)] struct Notification { message: String, #[serde(with = "time::serde::iso8601")] timestamp: OffsetDateTime, } fn main() { let input = r#"{ "message": "foo", "timestamp": "2022-01-02T11:12:13Z" }"#; let notification: Notification = serde_json::from_str(input).unwrap(); println!("{:?}", notification.timestamp); }