Rust 使用 chrono 處理日期時間

chrono 旨在成爲時間庫的一個功能完整的超集。它嚴格遵守 ISO 8601,默認包含時區,也有不含時區的類型。

1,先來一個小點心,測量函數耗費時間,使用的標準庫 time。

use std::thread;
use std::time::{Duration, Instant};
fn expensive_function() {
    thread::sleep(Duration::from_secs(1));
}
fn main() {
    let start = Instant::now();
    expensive_function();
    let duration = start.elapsed();
    println!("Time elapsed in expensive_function() is: {:?}", duration);
}
// 打印結果
Time elapsed in expensive_function() is: 1.0122099s

2,獲取當前時間

use chrono::prelude::*;
let utc: DateTime<Utc> = Utc::now(); // e.g. `2014-11-28T12:45:59.324310806Z`
let local: DateTime<Local> = Local::now(); // e.g. `2014-11-28T21:45:59.324310806+09:00`
println!("the utc is {},the local is {}", utc, local);
// 打印結果
the utc is 2023-07-01 01:50:40.050821800 UTC,the local is 2023-07-01 09:50:40.050837400 +08:00

3,日期計算,計算 1 周後,3 天前等。

use chrono::{Duration, Local};
fn main() {
    let now = Local::now();
    println!("{}", now);
    let after_one_week = now.checked_add_signed(Duration::weeks(1)).unwrap();
    let three_day_earlier = now.checked_sub_signed(Duration::days(3)).unwrap();
    println!(
        "now is {},now after one week is {},and now before three days is {}.",
        now, after_one_week, three_day_earlier
    );
}
// 打印結果
now is 2023-07-01 09:54:01.195332500 +08:00,now after one week is 2023-07-08 09:54:01.195332500 +08:00,and now before three days is 2023-06-28 09:54:01.195332500 
+08:00.

4,日期和時間戳相互轉換

use chrono::{DateTime, TimeZone, Utc};
fn main() {
    // 時間戳轉爲日期
    let dt = Utc.timestamp_opt(1_500_000_000, 0).unwrap();
    println!("the date is {}.", dt.to_rfc2822());
    // 日期轉爲時間戳
    let dt = DateTime::parse_from_rfc2822("Fri, 14 Jul 2017 02:40:00 +0000").unwrap();
    println!("the timestamp is {}.", dt.timestamp());
}
// 打印結果
the date is Fri, 14 Jul 2017 02:40:00 +0000.
the timestamp is 1500000000.

5,日期格式化

use chrono::{DateTime, Local, Utc};
fn main() {
    let now: DateTime<Utc> = Utc::now();
    println!("UTC now is: {}", now);
    println!("UTC now in RFC 2822 is: {}", now.to_rfc2822());
    println!("UTC now in RFC 3339 is: {}", now.to_rfc3339());
    println!(
        "UTC now in a custom format is: {}",
        now.format("%a %b %e %T %Y")
    );
    println!(
        "UTC now in a custom format is: {}",
        now.format("%Y-%m-%d %H:%M:%S")
    );
    let now = Local::now();
    println!("Local now is: {}", now);
    println!("Local now in RFC 2822 is: {}", now.to_rfc2822());
    println!("Local now in RFC 3339 is: {}", now.to_rfc3339());
    println!(
        "Local now in a custom format is: {}",
        now.format("%a %b %e %T %Y")
    );
    println!(
        "Local now in a custom format is: {}",
        now.format("%Y-%m-%d %H:%M:%S")
    );
}
// 打印結果
UTC now is: 2023-07-01 02:12:41.864372800 UTC
UTC now in RFC 2822 is: Sat, 01 Jul 2023 02:12:41 +0000
UTC now in RFC 3339 is: 2023-07-01T02:12:41.864372800+00:00
UTC now in a custom format is: Sat Jul  1 02:12:41 2023
UTC now in a custom format is: 2023-07-01 02:12:41
Local now is: 2023-07-01 10:12:41.865922200 +08:00
Local now in RFC 2822 is: Sat, 01 Jul 2023 10:12:41 +0800
Local now in RFC 3339 is: 2023-07-01T10:12:41.865922200+08:00
Local now in a custom format is: Sat Jul  1 10:12:41 2023
Local now in a custom format is: 2023-07-01 10:12:41

6,字符串轉爲日期

use chrono::format::ParseError;
use chrono::{DateTime, FixedOffset, TimeZone, Utc};
fn main() -> Result<(), ParseError> {
    // 方法1
    let date1 = "2014-11-28T12:00:09Z".parse::<DateTime<Utc>>().unwrap();
    println!("date1 is {}.", date1);
    let date2 = "2014-11-28T21:00:09+09:00"
        .parse::<DateTime<Utc>>()
        .unwrap();
    println!("date2 is {}.", date2);
    let date3 = "2014-11-28T21:00:09+09:00"
        .parse::<DateTime<FixedOffset>>()
        .unwrap();
    println!("date3 is {}.", date3);
    // 方法2
    let date1 =
        DateTime::parse_from_str("2014-11-28 21:00:09 +09:00", "%Y-%m-%d %H:%M:%S %z").unwrap();
    println!("date1 is {}.", date1);
    let date2 = DateTime::parse_from_rfc2822("Fri, 28 Nov 2014 21:00:09 +0900").unwrap();
    println!("date2 is {}.", date2);
    let date3 = DateTime::parse_from_rfc3339("2014-11-28T21:00:09+09:00").unwrap();
    println!("date3 is {}.", date3);
    // 方法3
    let date1 = Utc
        .datetime_from_str("2014-11-28 12:00:09", "%Y-%m-%d %H:%M:%S")
        .unwrap();
    println!("date1 is {}.", date1);
    let date2 = Utc
        .datetime_from_str("Fri Nov 28 12:00:09 2014", "%a %b %e %T %Y")
        .unwrap();
    println!("date2 is {}.", date2);
    Ok(())
}
// 打印結果
date1 is 2014-11-28 12:00:09 UTC.
date2 is 2014-11-28 12:00:09 UTC.
date3 is 2014-11-28 21:00:09 +09:00.
date1 is 2014-11-28 21:00:09 +09:00.
date2 is 2014-11-28 21:00:09 +09:00.
date3 is 2014-11-28 21:00:09 +09:00.
date1 is 2014-11-28 12:00:09 UTC.
date2 is 2014-11-28 12:00:09 UTC.

7,獲取日期的年月日和時分秒等信息

use chrono::{Datelike, FixedOffset, NaiveDate, TimeZone, Timelike};
fn main() {
    let now = FixedOffset::east_opt(9 * 3600)
        .unwrap()
        .from_local_datetime(
            &NaiveDate::from_ymd_opt(2014, 11, 28)
                .unwrap()
                .and_hms_nano_opt(21, 45, 59, 324310806)
                .unwrap(),
        )
        .unwrap();
    println!("now is {}.", now);
    // 獲取時分秒
    let (is_pm, hour) = now.hour12();
    println!(
        "The current time is {:02}:{:02}:{:02} {}",
        hour,
        now.minute(),
        now.second(),
        if is_pm { "PM" } else { "AM" }
    );
    println!(
        "And there have been {} seconds since midnight",
        now.num_seconds_from_midnight()
    );
    let (is_common_era, year) = now.year_ce();
    println!(
        "The current date is {}-{:02}-{:02} {:?} ({})",
        year,
        now.month(),
        now.day(),
        now.weekday(),
        if is_common_era { "CE" } else { "BCE" }
    );
    println!(
        "The week of year is {:?},and the day of year is {}",
        now.iso_week(),
        now.ordinal(),
    );
    println!(
        "And the Common Era began {} days ago",
        now.num_days_from_ce()
    );
}
// 打印結果
now is 2014-11-28 21:45:59.324310806 +09:00.
The current time is 09:45:59 PM
And there have been 78359 seconds since midnight
The current date is 2014-11-28 Fri (CE)
The week of year is 2014-W48,and the day of year is 332
And the Common Era began 735565 days ago

更多內容請查看 https://docs.rs/chrono/0.4.26/chrono/

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