There are different ways of formatting date and time in Rust using external crates. But I prefer to use the chrono crate . In order to use the chrono crate ( or any external crate ), we first need to add it to our project.
Adding an external crate
1) Open a terminal in Visual Studio Code.
2) Paste the line cargo add chrono ; and the chrono crate shall be added to your project
This can also be done by the command line.
1) Open a command prompt and navigate to the directory of your project.
2) Paste the line cargo add chrono ; and the chrono crate shall be added to your project
Importing the necessary structs
Depending on how you to like to use the chrono , we have to import the necessary strutcs to our project.
use chrono::{DateTime,Local, Duration};
In the above use statement, we want to use the DateTime, Local and Duration structs.
If you want to use the UTC namespace instead of the Local, the reference shall be as below
use chrono::{DateTime,UTC, Duration};
The comma between DateTime, UTC and Duration means that we are importing all the three structs.
Formatting the date
let current_date: DateTime<Local> = chrono::Local::now();
let formatted_date = current_date.format("%Y-%m-%d").to_string();
In the first line ,I have assigned the Local date time to current date.
In the second line, I have formatted the date for Year, Month and Date. The formatting flags can be used according to your needs.
No comments :
Post a Comment