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 theDateTimeandUtctypes from thechronocrate.let now: DateTime<Utc> = Utc::now();- This creates aDateTimeobject with the current time in UTC.let formatted_time = now.format("%Y-%m-%d %H:%M:%S").to_string();- This uses theformatmethod to format theDateTimeobject to a string with the specified format and then converts it to aStringobject.
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...