rustHow to format date in Rust
Rust provides a number of ways to format dates.
The most common way is to use the chrono
crate. This crate provides a number of functions to format dates and times.
Example code
use chrono::{DateTime, Utc};
let now: DateTime<Utc> = Utc::now();
let formatted_date = now.format("%Y-%m-%d %H:%M:%S").to_string();
println!("Formatted date: {}", formatted_date);
Output example
Formatted date: 2020-09-17 15:45:12
The code above uses the chrono
crate to get the current date and time in UTC and then formats it using the format
function. The format string %Y-%m-%d %H:%M:%S
specifies the format of the output.
Code explanation
use chrono::{DateTime, Utc};
: imports theDateTime
andUtc
types from thechrono
crate.let now: DateTime<Utc> = Utc::now();
: gets the current date and time in UTC.let formatted_date = now.format("%Y-%m-%d %H:%M:%S").to_string();
: formats the date and time using theformat
function and converts it to a string.println!("Formatted date: {}", formatted_date);
: prints the formatted date.
Helpful links
Related
- How to get time from milliseconds in Rust
- How to sleep in Rust
- How to get execution time in Rust
- Using now to get current time in Rust
- How to get current date in Rust
- How to convert timestamp to datetime in Rust
- How to add second to time in Rust
- How to add day to date in Rust
- How to convert datetime to timestamp in Rust
More of Rust
- How to match the end of a line in a Rust regex?
- How to parse JSON string in Rust?
- How to modify an existing entry in a Rust HashMap?
- How to sort the keys in a Rust HashMap?
- How to declare a Rust slice?
- How to create a subslice from a Rust slice?
- How to calculate the sum of a Rust slice?
- How to get the first element of a slice in Rust?
- How to get the last element of a Rust slice?
- How to convert the keys of a Rust HashMap to a vector?
See more codes...