Rust 中日期和时间处理入门
日期和时间处理是大多数现代应用程序中的关键任务之一。无论是事件日志记录、截止日期计算、API 时间戳处理还是日历操作,都离不开高质量的时间处理库。在 Rust 生态系统中,标准库仅提供基本功能 (std::time::Instant 和 std::time::Duration),这些适用于性能测量,但不适合完整的日历日期处理。
这时 chrono crate 就派上用场了——它是 Rust 中日期和时间处理的事实标准。它提供了广泛的功能:从创建简单日期到处理时区、格式化和算术运算。在本文中,我们将详细讨论 chrono 的主要功能,提供实际示例,并展示如何避免常见错误。
1. chrono 的安装和基本类型
首先,将依赖项添加到您的 Cargo.toml 中:
[dependencies]chrono = "0.4"之后,您可以导入所需的类型。Chrono 提供了三种表示日期和时间的关键类型:
NaiveDate— 不带时间的日期(年、月、日)。NaiveDateTime— 不考虑时区的日期和时间。DateTime<Tz>— 带时区的日期和时间(例如Utc或Local)。
让我们看一个创建这些类型的简单示例:
use chrono::{NaiveDate, NaiveDateTime, DateTime, Utc, Local};
fn main() { // 创建 naive 日期(不带时间) let date = NaiveDate::from_ymd_opt(2025, 10, 15).unwrap(); println!("日期: {}", date);
// 创建 naive 时间(不带日期) let time = NaiveTime::from_hms_opt(14, 30, 0).unwrap(); println!("时间: {}", time);
// 组合成 NaiveDateTime let naive_dt = NaiveDateTime::new(date, time); println!("Naive datetime: {}", naive_dt);
// 当前 UTC 时间和本地时间 let now_utc: DateTime<Utc> = Utc::now(); let now_local: DateTime<Local> = Local::now(); println!("当前 UTC: {}", now_utc); println!("当前本地时间: {}", now_local);}请注意使用 from_ymd_opt 和 from_hms_opt——它们返回 Option,这可以防止创建无效日期(例如 1 月 32 日)。
2. 日期格式化和解析
Chrono 使用基于说明符的强大格式化系统,与 C/PHP 中的 strftime 非常相似。这允许灵活地将日期转换为字符串,反之亦然。
2.1 将日期格式化为字符串
use chrono::{Utc, DateTime};
fn main() { let now: DateTime<Utc> = Utc::now(); // 标准 ISO 8601 println!("ISO: {}", now.to_rfc3339()); // 自定义格式 println!("自定义: {}", now.format("%Y-%m-%d %H:%M:%S")); println!("星期几: {}", now.format("%A")); println!("月份: {}", now.format("%B")); println!("年-月-日: {}", now.format("%d.%m.%Y"));}主要格式化说明符:
%Y— 年份(4 位数字)%m— 月份(01-12)%d— 月份中的日期(01-31)%H— 小时(00-23)%M— 分钟(00-59)%S— 秒(00-60)%A— 星期几的全名%B— 月份的全名
2.2 将字符串解析为日期
对于反向转换,使用 parse_from_str 方法:
use chrono::{NaiveDateTime, DateTime, Utc, format::ParseResult};