You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Rust的chrono crate将DateTime<Utc>转换为NaiveDate?

使用Rust的chrono crate将DateTime<Utc>转换为NaiveDate

最直接的方式是调用DateTime<Utc>实例的date_naive()方法,补全后的测试代码如下:

#[test]
fn test_utc_now_to_naive_date() {
  let utc_now = Utc::now();
  let now: NaiveDate = utc_now.date_naive();
}

如果想借助Datelike trait提供的方法手动构造NaiveDate,也可以这么写(不过显然前者更简洁):

let now: NaiveDate = NaiveDate::from_ymd_opt(utc_now.year(), utc_now.month(), utc_now.day()).unwrap();

确实不少日期时间库存在过度设计的问题,chrono里这个转换方法不算显眼,容易让人走弯路。

内容的提问来源于stack exchange,提问作者BitTickler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 13:03:32