如何从 Chrono::DateTime 获取年、月和日期组件?

问题描述

The documentation 没有提及这个话题。我是否需要将其转换为 Date<Tz>?即便如此,也没有函数可以从中获取年份组件。

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

解决方法

您需要 DateLike 特性并使用其 methods。检索 Date 组件以对其进行操作:

use chrono::Datelike;
use chrono; // 0.4.19

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

Playground