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 use regex to match a double quote in Rust?
- How to create a HashMap of structs in Rust?
- How to replace a capture group using Rust regex?
- How to match the end of a line in a Rust regex?
- How to modify an existing entry in a Rust HashMap?
- How do I identify unused variables in Rust?
- How to use negation in Rust regex?
- Regex example to match multiline string in Rust?
- How to use a Rust HashMap in a struct?
- How do I use a variable number of arguments in Rust?
See more codes...