6

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
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
DennyHiu
  • 4,861
  • 8
  • 48
  • 80
  • 1
    Also, the docs [have search functionality](https://docs.rs/chrono/0.4.19/chrono/struct.DateTime.html?search=year), FWIW. – Shepmaster May 11 '21 at 14:15

1 Answers1

11

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::*;.

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
Netwave
  • 40,134
  • 6
  • 50
  • 93
  • 1
    See also [How can I get the current weekday in Rust using the Chrono crate?](https://stackoverflow.com/q/66181608/155423) – Shepmaster May 11 '21 at 14:14