How to format a date using different formats in Rust

1 Answer

0 votes
use chrono::{DateTime, Local};

fn main() {
    // Get current local datetime
    let now: DateTime<Local> = Local::now();

    println!("Original datetime: {}\n", now);

    // --- BASIC COMPONENTS ---

    println!("Year (4 digits): {}", now.format("%Y"));      
    println!("Year (2 digits): {}", now.format("%y"));       

    println!("Month (01-12): {}", now.format("%m"));         
    println!("Month name (short): {}", now.format("%b"));    
    println!("Month name (full): {}", now.format("%B"));     

    println!("Day of month: {}", now.format("%d"));         
    println!("Day of week (short): {}", now.format("%a"));   
    println!("Day of week (full): {}", now.format("%A"));    

    // --- COMMON FULL FORMATS ---

    println!("YYYY-MM-DD: {}", now.format("%Y-%m-%d"));
    println!("DD/MM/YYYY: {}", now.format("%d/%m/%Y"));
    println!("MM-DD-YYYY: {}", now.format("%m-%d-%Y"));

    println!(
        "YYYY/MM/DD HH:MM:SS: {}",
        now.format("%Y/%m/%d %H:%M:%S")
    );

    // --- TIME FORMATS ---

    println!("24-hour time: {}", now.format("%H:%M:%S"));
    println!("12-hour time: {}", now.format("%I:%M:%S %p"));

    // --- HUMAN-READABLE TEXT FORMATS ---

    println!(
        "Full readable date: {}",
        now.format("%A, %B %d, %Y")
    );

    println!(
        "Full date + time: {}",
        now.format("%A, %B %d, %Y %H:%M:%S")
    );

    // --- WEEK / YEAR INFO ---

    println!("Day of year: {}", now.format("%j"));   
    println!("Week number: {}", now.format("%U"));   
    println!("ISO week number: {}", now.format("%V")); 

    // --- STANDARD FORMATS (RFC / ISO) ---

    println!("RFC 2822: {}", now.to_rfc2822());
    println!("RFC 3339: {}", now.to_rfc3339());
    println!("ISO 8601-like: {}", now.format("%Y-%m-%dT%H:%M:%S%:z"));

    // --- CUSTOM WITH TIMEZONE ---

    println!(
        "With timezone: {}",
        now.format("%Y-%m-%d %H:%M:%S %Z")
    );
}



/*
run:

Original datetime: 2026-05-20 15:49:40.600103859 +00:00

Year (4 digits): 2026
Year (2 digits): 26
Month (01-12): 05
Month name (short): May
Month name (full): May
Day of month: 20
Day of week (short): Wed
Day of week (full): Wednesday
YYYY-MM-DD: 2026-05-20
DD/MM/YYYY: 20/05/2026
MM-DD-YYYY: 05-20-2026
YYYY/MM/DD HH:MM:SS: 2026/05/20 15:49:40
24-hour time: 15:49:40
12-hour time: 03:49:40 PM
Full readable date: Wednesday, May 20, 2026
Full date + time: Wednesday, May 20, 2026 15:49:40
Day of year: 140
Week number: 20
ISO week number: 21
RFC 2822: Wed, 20 May 2026 15:49:40 +0000
RFC 3339: 2026-05-20T15:49:40.600103859+00:00
ISO 8601-like: 2026-05-20T15:49:40+00:00
With timezone: 2026-05-20 15:49:40 +00:00

*/

 



answered 6 hours ago by avibootz
...