Rust 中处理时间格式化主要用chrono(最流行)和time两个库。标准库std::time只提供时间戳,没有格式化能力。
一、chrono(推荐)
rust
use chrono::{Local, Utc, NaiveDateTime, DateTime}; fn main() { // 1. 当前时间格式化 let now = Local::now(); println!("{}", now.format("%Y-%m-%d %H:%M:%S")); // 2026-08-10 11:57:30 println!("{}", now.format("%Y年%m月%d日")); // 2026年08月10日 println!("{}", now.format("%a, %d %b %Y %H:%M:%S %z")); // Mon, 10 Aug 2026 11:57:30 +0800 println!("{}", now.format("%+")); // RFC3339 格式 println!("{}", now.to_rfc3339()); // 同上 println!("{}", now.to_rfc2822()); // RFC2822 格式 // 2. UTC 时间 let utc = Utc::now(); println!("{}", utc.format("%Y-%m-%d %H:%M:%S UTC")); // 3. 字符串解析为时间 let dt = NaiveDateTime::parse_from_str( "2026-08-10 11:57:00", "%Y-%m-%d %H:%M:%S" ).unwrap(); println!("{}", dt); // 4. 自定义时区解析 let dt: DateTime<Utc> = "2026-08-10T11:57:00Z".parse().unwrap(); }Cargo.toml:
toml
[dependencies] chrono = "0.4"二、time crate(0.3+ 版本)
rust
use time::{OffsetDateTime, format_description}; fn main() { let now = OffsetDateTime::now_utc(); // 1. 使用预定义格式 println!("{}", now.format(&time::format_description::well_known::Rfc3339).unwrap()); // 2. 自定义格式 let fmt = format_description::parse("[year]-[month]-[day] [hour]:[minute]:[second]").unwrap(); println!("{}", now.format(&fmt).unwrap()); // 2026-08-10 11:57:30 // 3. 解析 let parsed = OffsetDateTime::parse("2026-08-10T11:57:00Z", &time::format_description::well_known::Rfc3339).unwrap(); }Cargo.toml:
toml
[dependencies] time = { version = "0.3", features = ["formatting", "parsing"] }三、常用格式说明符(chrono)
表格
| 说明符 | 含义 | 示例 |
|---|---|---|
%Y | 四位年份 | 2026 |
%m | 月份(01-12) | 08 |
%d | 日期(01-31) | 10 |
%H | 小时(00-23) | 11 |
%M | 分钟(00-59) | 57 |
%S | 秒(00-59) | 30 |
%f | 微秒(6位) | 123456 |
%.3f | 毫秒(3位) | 123 |
%z | 时区偏移 | +0800 |
%Z | 时区名称 | CST |
%a | 星期缩写 | Mon |
%A | 星期全称 | Monday |
%b | 月份缩写 | Aug |
%B | 月份全称 | August |
%s | Unix 时间戳 | 1723260420 |
四、标准库(仅时间戳,无格式化)
rust
use std::time::{SystemTime, UNIX_EPOCH}; fn main() { let now = SystemTime::now(); let since_epoch = now.duration_since(UNIX_EPOCH).unwrap(); println!("{}", since_epoch.as_secs()); // 1723260420 }选型建议
表格
| 场景 | 推荐 |
|---|---|
| 一般日期时间处理 | chrono |
| 需要零依赖/更轻量 | time |
| 只需要时间戳计算 | 标准库std::time |
chrono生态最成熟,文档和示例最多,新手首选。