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

Den*_*Hiu 6 rust rust-chrono

该文档没有提及任何有关此主题的内容。我需要将其转换为 吗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();
Run Code Online (Sandbox Code Playgroud)
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();
Run Code Online (Sandbox Code Playgroud)

Net*_*ave 14

你需要这个DateLike特质并使用它的方法。检索Date要使用它进行操作的组件:

use chrono::Datelike;

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

操场

此特性可用于chrono::prelude,因此您可以改为use chrono::prelude::*;.