Rust Date & Time
Tags: rust, datetime
Published: 2023-01-14 14:55:33

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

```rust
    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"));
```

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

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

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

```rust
    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"));
```

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

```rust
    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"));
```

Create custom date time, with specific timezone as below

```rust
    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"));
```

#### 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

```rust
    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:?}");
```

###### Parse a String of format `yyyy-mm-dd` to Date

```rust
    let curr_date = NaiveDate::parse_from_str("2023-01-01", "%Y-%m-%d").unwrap();
    println!("Parse Date from String: {curr_date:?}");
```

###### Parse a String of format `dd-mm-yyyy` to Date

```rust
    let curr_date = NaiveDate::parse_from_str("01-01-2023", "%d-%m-%Y").unwrap();
    println!("Parse Date from String: {curr_date:?}");
```

###### Parse a String of format `MMM-dd-yyyy` to Date

```rust
    let curr_date = NaiveDate::parse_from_str("Jan-01-2023", "%b-%d-%Y").unwrap();
    println!("Parse Date from String: {curr_date:?}");
```

###### Parse a String of format `HH:mm:ss` to Time

```rust
    let curr_time= NaiveTime::parse_from_str("12:00:00", "%H:%M:%S").unwrap();
    println!("Parse Time from String: {curr_time:?}");
```

###### Parse a String of format `HH:mm:ss+tz` to Time

```rust
    let curr_time= NaiveTime::parse_from_str("12:00:00+0800", "%H:%M:%S%z").unwrap();
    println!("Parse Time from String: {curr_time:?}");
```

###### ParseRFC2822 formatted string to DateTime 

```rust
    let now = DateTime::parse_from_rfc2822("Sun, 1 Jan 2023 12:00:00 +0800").unwrap();
    println!("Parse RFC2822 formatted Date/Time from String: {now:?}");
```

###### ParseRFC3339 formatted string to DateTime

```rust
    let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00+08:00").unwrap();
    println!("Parse RFC3339 formatted Date/Time from String: {now:?}");
```

#### Create DateTime from Timestamp

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

```rust
    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:?}");
```

#### DateTime manipulation: Add Day/Month

It is possible to do DateTime manipulation by using Chrono crate

```rust
    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:?}");
```

#### DateTime manipulation: Subtract Day/Month

It is possible to do DateTime manipulation by using Chrono crate

```rust
    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:?}");
```

#### DateTime comparison

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

```rust
    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");
    }
```

All the code examples can be found in this [link](https://github.com/sivakumar-sivaprakasam/rust-examples/tree/main/datetime)

Please feel free to share your feedback.

Happy reading!!!