rust时间格式
Rust 中处理时间格式化主要用chrono最流行和time两个库。标准库std::time只提供时间戳没有格式化能力。一、chrono推荐rustuse 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: DateTimeUtc 2026-08-10T11:57:00Z.parse().unwrap(); }Cargo.tomltoml[dependencies] chrono 0.4二、time crate0.3 版本rustuse 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.tomltoml[dependencies] time { version 0.3, features [formatting, parsing] }三、常用格式说明符chrono表格说明符含义示例%Y四位年份2026%m月份01-1208%d日期01-3110%H小时00-2311%M分钟00-5957%S秒00-5930%f微秒6位123456%.3f毫秒3位123%z时区偏移0800%Z时区名称CST%a星期缩写Mon%A星期全称Monday%b月份缩写Aug%B月份全称August%sUnix 时间戳1723260420四、标准库仅时间戳无格式化rustuse 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::timechrono生态最成熟文档和示例最多新手首选。