format a date in to the format 'yyyy-mm-dd' in rust

You can use the Chrono crate in Rust for working with dates and times. To format a date in the 'yyyy-mm-dd' format, you can use the format method on a NaiveDate instance.

Here is an example code snippet that shows how to format a date in the 'yyyy-mm-dd' format using Chrono:

main.rs
use chrono::{NaiveDate, ParseError};

fn main() -> Result<(), ParseError> {
    let date_str = "2021-01-01";
    let date = NaiveDate::parse_from_str(date_str, "%Y-%m-%d")?;
    let formatted_date = date.format("%Y-%m-%d").to_string();

    println!("Formatted date: {}", formatted_date); // Output: Formatted date: 2021-01-01

    Ok(())
}
341 chars
12 lines

In this example, we start by importing the necessary modules from Chrono. We then parse a date string using NaiveDate::parse_from_str, which returns a NaiveDate instance. We then use the format method on this instance to format the date string in the desired format. Finally, we print the formatted date string to the console.

gistlibby LogSnag