Rust 日期与时间处理完全指南

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

Rust 中日期与时间操作入门

处理日期和时间是任何现代应用程序的核心任务之一。无论是事件记录、任务调度、用户数据处理,还是与 API 交互——正确处理时间戳都至关重要。在以高性能和安全性著称的 Rust 语言中,标准库仅提供了有限的时间处理工具。不过,功能强大的 chrono crate 应运而生,它已成为 Rust 生态系统中处理日期和时间的事实标准。

本文将详细介绍如何安装和使用 chrono,包括如何创建、格式化、解析和操作日期,以及如何处理时区和 Unix 时间戳。



安装并添加 chrono crate

首先,需要在项目的 Cargo.toml 文件中添加 chrono 依赖:

[dependencies]chrono = "0.4"

然后,在代码中导入必要的类型和 trait:

use chrono::{DateTime, Utc, Local, NaiveDate, NaiveDateTime, Duration, Datelike, Timelike, TimeZone};

chrono crate 提供了几种表示日期和时间的关键类型:

  • NaiveDate — 不含时间和时区的日期(例如 2024-01-15)。
  • NaiveTime — 不含日期和时区的时间(例如 14:30:00)。
  • NaiveDateTime — 不考虑时区的日期和时间组合。
  • DateTime<Utc> — 带 UTC 时区的日期和时间。
  • DateTime<Local> — 带系统本地时区的日期和时间。
  • DateTime<FixedOffset> — 带任意 UTC 偏移量的日期和时间。


创建并获取当前时间

获取当前时刻最简单的方法是使用 Utc::now() 和 Local::now() 函数:

use chrono::{Utc, Local};

fn main() { let utc_now: DateTime<Utc> = Utc::now(); let local_now: DateTime<Local> = Local::now(); println!("当前 UTC 时间: {}", utc_now); println!("当前本地时间: {}", local_now);}

要创建特定日期,可以使用 NaiveDate::from_ymd 和 NaiveDateTime::new 方法:

use chrono::{NaiveDate, NaiveDateTime, NaiveTime};

fn main() { // 创建日期 2024 年 3 月 15 日 let date = NaiveDate::from_ymd(2024, 3, 15); println!("日期: {}", date); // 创建时间 10:30:00 let time = NaiveTime::from_hms(10, 30, 0); println!("时间: {}", time); // 组合日期和时间 let datetime = NaiveDateTime::new(date, time); println!("日期和时间: {}", datetime);}

还可以通过日期的 and_hms 方法创建带时区的日期:

use chrono::{Utc, TimeZone};

fn main() { let datetime_utc = Utc.ymd(2024, 12, 25).and_hms(12, 0, 0); println!("圣诞节 UTC 时间: {}", datetime_utc);}


格式化与解析日期

格式化输出

要将日期转换为字符串,可使用 format 方法,该方法接受一个格式字符串。格式说明符与 Python 等语言类似:

use chrono::{Utc, DateTime};

fn main() { let now = Utc::now(); // 基本格式化 println!("默认格式: {}", now.format("%Y-%m-%d %H:%M:%S")); println!("仅日期: {}", now.format("%d.%m.%Y")); println!("带月份名称: {}", now.format("%d %B %Y")); println!("带秒的时间: {}", now.format("%H:%M:%S")); println!("Unix 时间戳: {}", now.timestamp());}

博客

书籍推荐