rustHow to format time to string in Rust
Formatting time to string in Rust can be done using the chrono
crate. This crate provides a format
method which takes a DateTime
object and a formatting string as parameters and returns a String
object.
Code example:
use chrono::{DateTime, Utc};
let now: DateTime<Utc> = Utc::now();
let formatted_time = now.format("%Y-%m-%d %H:%M:%S").to_string();
Output
formatted_time
will contain a string in the format YYYY-MM-DD HH:MM:SS
Explanation of code parts:
use chrono::{DateTime, Utc};
- This imports theDateTime
andUtc
types from thechrono
crate.let now: DateTime<Utc> = Utc::now();
- This creates aDateTime
object with the current time in UTC.let formatted_time = now.format("%Y-%m-%d %H:%M:%S").to_string();
- This uses theformat
method to format theDateTime
object to a string with the specified format and then converts it to aString
object.
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...