Rust Date & Time

ssivakumar

Sivakumar

Posted on January 14, 2023

Rust Date & Time

In this blog post, let us explore how to work with Date & Time in Rust

Creating DateTime using Standard library and using Chrono crate

It is possible to create DateTime using various approaches. The first thing is by using standard librarie's SystemTime struct. Create DateTime using SystemTime and then by using chrono crate's DateTime to format the DateTime value

    let curr_time = SystemTime::now();
    let dt: DateTime<Utc> = curr_time.clone().into();
    println!("Date/Time created using SystemTime: {}", dt.format("%d-%b-%Y %H:%M:%S %P %z"));
Enter fullscreen mode Exit fullscreen mode

The another approach is, by using chrono crate's Utc struct

    let now = Utc::now();
    println!("Date/Time created using UTC: {}", now.format("%d-%b-%Y %H:%M:%S %P %z"));
Enter fullscreen mode Exit fullscreen mode

It is also possible to create DateTime with specific timezone. In this below example, we're creating DateTime with Singapore timezone

    let now = Utc::now().with_timezone(&Singapore);
    println!("Date/Time with specific timezone created using UTC: {}", now.format("%d-%b-%Y %H:%M:%S %P %z"));
Enter fullscreen mode Exit fullscreen mode

In case if you would like to create DateTime by using custom inputs, we can achieve it by using with_ymd_and_hms method

    let now = Utc.with_ymd_and_hms(2023, 1, 1, 12, 0, 0).unwrap();
    println!("Custom Date/Time created using UTC: {}", now.format("%d-%b-%Y %H:%M:%S %P %z"));
Enter fullscreen mode Exit fullscreen mode

Create custom date time, with specific timezone as below

    let now = Singapore.with_ymd_and_hms(2023, 1, 1, 12, 0, 0).unwrap();
    println!("Custom Date/Time with specific timezone created using UTC: {}", now.format("%d-%b-%Y %H:%M:%S %P %z"));
Enter fullscreen mode Exit fullscreen mode

Create DateTime from String

If you have DateTime value stored in String and you would like to convert it to DateTime type, it can be done using various ways.

Parse a String of format dd-MMM-yyyy HH:mm:ss +tz to DateTime
    let now = DateTime::parse_from_str("01-Jan-2023 12:00:00 pm +0800", "%d-%b-%Y %H:%M:%S %P %z").unwrap();
    println!("Parse Date/Time from String: {now:?}");
Enter fullscreen mode Exit fullscreen mode
Parse a String of format yyyy-mm-dd to Date
    let curr_date = NaiveDate::parse_from_str("2023-01-01", "%Y-%m-%d").unwrap();
    println!("Parse Date from String: {curr_date:?}");
Enter fullscreen mode Exit fullscreen mode
Parse a String of format dd-mm-yyyy to Date
    let curr_date = NaiveDate::parse_from_str("01-01-2023", "%d-%m-%Y").unwrap();
    println!("Parse Date from String: {curr_date:?}");
Enter fullscreen mode Exit fullscreen mode
Parse a String of format MMM-dd-yyyy to Date
    let curr_date = NaiveDate::parse_from_str("Jan-01-2023", "%b-%d-%Y").unwrap();
    println!("Parse Date from String: {curr_date:?}");
Enter fullscreen mode Exit fullscreen mode
Parse a String of format HH:mm:ss to Time
    let curr_time= NaiveTime::parse_from_str("12:00:00", "%H:%M:%S").unwrap();
    println!("Parse Time from String: {curr_time:?}");
Enter fullscreen mode Exit fullscreen mode
Parse a String of format HH:mm:ss+tz to Time
    let curr_time= NaiveTime::parse_from_str("12:00:00+0800", "%H:%M:%S%z").unwrap();
    println!("Parse Time from String: {curr_time:?}");
Enter fullscreen mode Exit fullscreen mode
ParseRFC2822 formatted string to DateTime
    let now = DateTime::parse_from_rfc2822("Sun, 1 Jan 2023 12:00:00 +0800").unwrap();
    println!("Parse RFC2822 formatted Date/Time from String: {now:?}");
Enter fullscreen mode Exit fullscreen mode
ParseRFC3339 formatted string to DateTime
    let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00+08:00").unwrap();
    println!("Parse RFC3339 formatted Date/Time from String: {now:?}");
Enter fullscreen mode Exit fullscreen mode

Create DateTime from Timestamp

In case if you have DateTime in timestamp value, it is possible to create DateTime from it

    let now = DateTime::parse_from_str("01-Jan-2023 12:00:00 pm +0800", "%d-%b-%Y %H:%M:%S %P %z").unwrap();
    let now_from_timestamp = NaiveDateTime::from_timestamp_millis(now.timestamp_millis());
    println!("Create Date/Time from Timestamp: {now_from_timestamp:?}");
Enter fullscreen mode Exit fullscreen mode

DateTime manipulation: Add Day/Month

It is possible to do DateTime manipulation by using Chrono crate

    let new_date = now.checked_add_days(Days::new(10)).and_then(|i| i.checked_add_months(Months::new(1)));
    println!("Add days and months to a Date/Time: {new_date:?}");
Enter fullscreen mode Exit fullscreen mode

DateTime manipulation: Subtract Day/Month

It is possible to do DateTime manipulation by using Chrono crate

    let new_date = now.checked_sub_days(Days::new(10)).and_then(|i| i.checked_sub_months(Months::new(1)));
    println!("Subtract days and months from a Date/Time: {new_date:?}");
Enter fullscreen mode Exit fullscreen mode

DateTime comparison

If you would like to compare 2 DateTime values, it can be done by using the comparison operator

    let dt1 = Utc.with_ymd_and_hms(2023, 1, 1, 12, 0, 0).unwrap();
    let dt2 = Utc.with_ymd_and_hms(2023, 2, 1, 12, 0, 0).unwrap();
    if dt1 == dt2 {
        println!("{dt1:?} and {dt2:?} are same");
    } else {
        println!("{dt1:?} and {dt2:?} are NOT same");
    }
Enter fullscreen mode Exit fullscreen mode

All the code examples can be found in this link

Please feel free to share your feedback.

Happy reading!!!

💖 💪 🙅 🚩
ssivakumar
Sivakumar

Posted on January 14, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related