How to get the year, month, and date component from Chrono::DateTime?

3.7k Views Asked by At

The documentation doesn't say anything about this topic. Do I need to convert it into Date<Tz>? Even then, there is no function to get the year component from it.

let current_date = chrono::Utc::now();
let year = current_date.year();  //this is not working, it should output the current year with i32/usize type
let month = current_date.month();
let date = current_date.date();
no method named `month` found for struct `chrono::DateTime<chrono::Utc>` in the current scope
1

There are 1 best solutions below

1
On BEST ANSWER

You need the DateLike trait and use its methods. Retrieve the Date component to operate with it:

use chrono::Datelike;

fn main() {
    let current_date = chrono::Utc::now();
    println!("{}", current_date.year());
}

Playground

This trait is available in chrono::prelude, so you can instead use chrono::prelude::*;.