Time Formatting Parsing in Rust
Rust supports time formatting and parsing via the chrono
crate, which provides a more flexible and powerful alternative to the standard library’s time
module.
use chrono::prelude::*;
use chrono::format::strftime::StrftimeItems;
fn main() {
let p = println!;
// Here's a basic example of formatting a time
// according to RFC3339, using the corresponding format string.
let t = Utc::now();
p!("{}", t.to_rfc3339());
// Time parsing uses the same format strings as formatting.
let t1 = DateTime::parse_from_rfc3339("2012-11-01T22:08:41+00:00").unwrap();
p!("{}", t1);
// Format and parse use format strings. You can use predefined
// formats or create custom ones. The formats use the strftime
// syntax, which is different from Go's layout approach.
p!("{}", t.format("%I:%M%p"));
p!("{}", t.format("%a %b %e %H:%M:%S %Y"));
p!("{}", t.format("%Y-%m-%dT%H:%M:%S%.f%:z"));
let form = StrftimeItems::new("%I %M %p");
let t2 = Utc.datetime_from_str("8 41 PM", "%I %M %p").unwrap();
p!("{}", t2);
// For purely numeric representations you can also
// use standard string formatting with the extracted
// components of the time value.
println!("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}-00:00",
t.year(), t.month(), t.day(),
t.hour(), t.minute(), t.second());
// Parse will return an error on malformed input
// explaining the parsing problem.
let result = Utc.datetime_from_str("8:41PM", "%a %b %e %H:%M:%S %Y");
p!("{:?}", result.err());
}
To run this program, you’ll need to add the chrono
crate to your Cargo.toml
file:
[dependencies]
chrono = "0.4"
Then you can run the program using cargo run
:
$ cargo run
2023-06-11T12:34:56.789012345+00:00
2012-11-01 22:08:41 +00:00
12:34PM
Sun Jun 11 12:34:56 2023
2023-06-11T12:34:56.789012345+00:00
0000-01-01 20:41:00 UTC
2023-06-11T12:34:56-00:00
Some(ParseError(Invalid))
In Rust, we use the chrono
crate for advanced time and date operations. The chrono
crate provides a more flexible and powerful alternative to the standard library’s time
module.
The main differences from the Go version are:
- We use the
DateTime
struct fromchrono
instead of Go’stime.Time
. - Format strings in Rust use the strftime syntax, which is different from Go’s layout approach.
- Rust uses the
unwrap()
method to handle potential errors in parsing, which will panic if the parsing fails. In a real application, you’d want to handle these errors more gracefully. - The
StrftimeItems
struct is used to create a reusable format string.
Rust’s approach to time formatting and parsing is more similar to other languages like Python or Ruby, using the widely-adopted strftime syntax for format strings.