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 match whitespace with a regex in Rust?
- How to match a URL with a regex in Rust?
- How to use Unicode in a regex in Rust?
- How to get a capture group using Rust regex?
- How to use regex to match a double quote in Rust?
- How to perform matrix operations in Rust?
- Example of struct private field in Rust
- Pointer to array element in Rust
- How to replace a capture group using Rust regex?
- How to replace strings using Rust regex?
See more codes...