在 Rust 中如何使用日期和時間?

在這篇文章中,讓我們探索一下如何在 Rust 中使用 Date & Time。

使用標準庫和 Chrono 庫創建 DateTime

可以使用各種方法創建 DateTime。首先使用標準庫的 SystemTime 創建 DateTime,然後使用 chrono 庫的 DateTime 格式化日期時間值。

在 Cargo.toml 中加入 chrono 依賴庫:

[dependencies]
chrono = "0.4"

在 main.rs 中寫入如下代碼:

use chrono::{
    DateTime, Days, FixedOffset, Months, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, Utc,
};

fn main() {
    let curr_time = SystemTime::now();
    let dt: DateTime<Utc> = curr_time.clone().into();
    println!("Date/Time created using SystemTime: {}", dt.format("%d-%b-%Y %H:%M:%S %P %z"));
}

另一種方法是使用 chrono crate 的 Utc 結構:

let now = Utc::now();
println!("Date/Time created using UTC: {}", now.format("%d-%b-%Y %H:%M:%S %P %z"));

也可以創建帶有特定時區的 DateTime。在下面的例子中,我們將創建東八區的 DateTime:

let est = FixedOffset::east_opt(8 * 3600).unwrap();
let now = Utc::now().with_timezone(&est);
println!("Date/Time with specific timezone created using UTC: {}", now.format("%d-%b-%Y %H:%M:%S %P %z"));

如果你想通過使用自定義輸入來創建 DateTime,我們可以通過使用 with_ymd_and_hms 方法來實現:

let now = Utc.with_ymd_and_hms(2023, 1, 1, 12, 0, 0).unwrap();
println!("Custom Date/Time created using UTC: {}", now.format("%d-%b-%Y %H:%M:%S %P %z"));

創建具體時區的自定義日期時間,如下所示:

let now = est.with_ymd_and_hms(2023, 1, 1, 12, 0, 0).unwrap();
println!("Custom Date/Time with specific timezone created using UTC: {}", now.format("%d-%b-%Y %H:%M:%S %P %z"));`

從字符串創建日期時間

如果你有存儲在字符串中的 DateTime 值,你想將其轉換爲 DateTime 類型,可以使用下面的方法來完成。

解析 "dd- mm -yyyy HH:mm:ss +tz" 格式的字符串爲 DateTime:

let now = DateTime::parse_from_str("01-Jan-2023 12:00:00 pm +0800""%d-%b-%Y %H:%M:%S %P %z").unwrap();
println!("Parse Date/Time from String: {now:?}");

解析 "yyyy-mm-dd" 格式的字符串爲 Date:

let curr_date = NaiveDate::parse_from_str("2023-01-01""%Y-%m-%d").unwrap();
println!("Parse Date from String: {curr_date:?}");

解析 "dd-mm-yyyy" 格式的字符串爲 Date:

let curr_date = NaiveDate::parse_from_str("01-01-2023""%d-%m-%Y").unwrap();
println!("Parse Date from String: {curr_date:?}");

解析 "mm -dd-yyyy" 格式的字符串爲 Date:

let curr_date = NaiveDate::parse_from_str("Jan-01-2023""%b-%d-%Y").unwrap();
println!("Parse Date from String: {curr_date:?}");

解析 "HH:mm:ss" 格式的字符串爲 Time:

let curr_time= NaiveTime::parse_from_str("12:00:00""%H:%M:%S").unwrap();
println!("Parse Time from String: {curr_time:?}");

解析 "HH:mm:ss+tz" 格式的字符串爲 Time:

let curr_time= NaiveTime::parse_from_str("12:00:00+0800""%H:%M:%S%z").unwrap();
println!("Parse Time from String: {curr_time:?}");

解析 RFC2822 格式的字符串爲 DateTime:

let now = DateTime::parse_from_rfc2822("Sun, 1 Jan 2023 12:00:00 +0800").unwrap();
println!("Parse RFC2822 formatted Date/Time from String: {now:?}");

解析 RFC3339 格式的字符串爲 DateTime:

let now = DateTime::parse_from_rfc3339("2023-01-01T12:00:00+08:00").unwrap();
println!("Parse RFC3339 formatted Date/Time from String: {now:?}");

從 Timestamp 創建 DateTime

從時間戳值創建 DateTime

let now = DateTime::parse_from_str("01-Jan-2023 12:00:00 pm +0800""%d-%b-%Y %H:%M:%S %P %z").unwrap();
let now_from_timestamp = NaiveDateTime::from_timestamp_millis(now.timestamp_millis());
println!("Create Date/Time from Timestamp: {now_from_timestamp:?}");

日期時間計算

增加日 / 月

let new_date = now
        .checked_add_days(Days::new(10))
        .and_then(|i| i.checked_add_months(Months::new(1)));
println!("Add days and months to a Date/Time: {new_date:?}");

減少日 / 月

let new_date = now
        .checked_sub_days(Days::new(10))
        .and_then(|i| i.checked_sub_months(Months::new(1)));
println!("Subtract days and months from a Date/Time: {new_date:?}");

日期時間比較

如果你想比較 2 個 DateTime 值,可以使用比較操作符

let dt1 = Utc.with_ymd_and_hms(2023, 1, 1, 12, 0, 0).unwrap();
let dt2 = Utc.with_ymd_and_hms(2023, 2, 1, 12, 0, 0).unwrap();
if dt1 == dt2 {
    println!("{dt1:?} and {dt2:?} are same");
} else {
    println!("{dt1:?} and {dt2:?} are NOT same");
}

本文翻譯自:

https://dev.to/ssivakumar/rust-date-time-e2k


本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/uL3l8l0exEykWvZbSTkUUg