ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

rust时间格式

rust时间格式

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
%sUnix 时间戳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生态最成熟,文档和示例最多,新手首选。

返回列表