rustHow to format datetime string in Rust
Formatting a datetime string in Rust can be done using the chrono
crate. This crate provides a DateTime
type which can be used to parse and format datetime strings.
Below is an example of how to format a datetime string in Rust:
use chrono::{DateTime, Utc};
let datetime = Utc::now();
let formatted_datetime = datetime.format("%Y-%m-%d %H:%M:%S").to_string();
println!("Formatted datetime: {}", formatted_datetime);
Output
Formatted datetime: 2020-09-17 15:45:12
Explanation:
- The
chrono
crate is imported to use theDateTime
type. - The
Utc::now()
method is used to get the current datetime in UTC. - The
format()
method is used to format the datetime string according to the specified format string. - The
to_string()
method is used to convert the formatted datetime string to aString
type. - The formatted datetime string is printed using the
println!
macro.
Helpful links:
More of Rust
- How to get a capture group using Rust regex?
- How to use Unicode in a regex in Rust?
- How to get the last element of a Rust slice?
- How to match the end of a line in a Rust regex?
- How to replace a capture group using Rust regex?
- How to use non-capturing groups in Rust regex?
- How to use an enum in a Rust HashMap?
- How to match whitespace with a regex in Rust?
- How to split a string with Rust regex?
- How to match a URL with a regex in Rust?
See more codes...