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
chronocrate is imported to use theDateTimetype. - 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 aStringtype. - The formatted datetime string is printed using the
println!macro.
Helpful links:
More of Rust
- How to perform matrix operations in Rust?
- How to use regex to match a double quote in Rust?
- How to parse a file with Rust regex?
- How to sort a Rust HashMap?
- How to compare two Rust HashMaps?
- How to use non-capturing groups in Rust regex?
- How to escape a Rust regex?
- How to insert an element into a Rust HashMap if it does not already exist?
- How to replace strings using Rust regex?
- How to update struct in Rust
See more codes...