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

如何使用chrono 0.4.22获取UTC的Unix时间戳并解决编译报错

解决Chrono获取UTC Unix时间戳的问题

错误原因

你在Cargo.toml中关闭了chrono的默认特性(default-features = false),而Local模块属于默认特性包含的local组件,因此编译时无法找到该模块。不过如果你的需求仅为获取UTC时间的Unix时间戳,完全不需要依赖Local模块。

正确配置与代码

1. 调整Cargo.toml的Chrono依赖

关闭默认特性后,需要手动启用所需特性才能使用Utc::now()和Unix时间戳相关方法:

chrono = { version = "0.4.22", default-features = false, features = ["std", "clock"] }
  • std:提供标准库相关支持,是调用时间戳方法的基础
  • clock:允许通过Utc::now()获取当前UTC时间

2. 获取UTC时间的Unix时间戳代码

use chrono::Utc;

fn main() {
    // 获取当前UTC时间实例
    let utc_now = Utc::now();
    
    // 秒级Unix时间戳(i64类型)
    let timestamp_sec = utc_now.timestamp();
    println!("UTC秒级时间戳: {}", timestamp_sec);
    
    // 毫秒级Unix时间戳(i64类型)
    let timestamp_millis = utc_now.timestamp_millis();
    println!("UTC毫秒级时间戳: {}", timestamp_millis);
    
    // 纳秒级Unix时间戳(i64类型,注意:部分系统无法提供完整纳秒精度)
    let timestamp_nanos = utc_now.timestamp_nanos();
    println!("UTC纳秒级时间戳: {}", timestamp_nanos);
}

若需使用Local时间(可选)

如果之后需要用到Local模块,只需在Cargo.toml中添加local特性即可:

chrono = { version = "0.4.22", default-features = false, features = ["std", "clock", "local"] }

此时就能正常调用chrono::offset::Local::now()。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 08:35:21