Rust日期與時間的操作方法
介紹
Rust的時間操作主要用到chrono庫,接下來我將簡單選一些常用的操作進行介紹,如果想了解更多細節(jié),請查看官方文檔。
官方文檔:chrono - Rust
Cargo.toml引用:chrono = { version = "0.4", features = ["serde"] }
一、計算耗時
Rust標準庫,一般用于計算變量start和duration之間的程序運行時間,代碼如下:
use std::time::{Duration, Instant};
use std::thread;
fn expensive_function(seconds:u64) {
thread::sleep(Duration::from_secs(seconds));
}
fn main() {
cost();
}
fn cost(){
let start = Instant::now();
expensive_function(2);
let duration = start.elapsed();
println!("耗時: {:?}", duration);
}二、時間加減法
使用到chrono庫的checked_add_signed方法,如果無法計算出日期和時間,方法將返回 None。比如當前時間加一天、加兩周、加3小時再減4秒,代碼如下:
use chrono::{Duration, Local};
fn main() {
// 獲取當前時間
let now = Local::now();
println!("{}", now);
let almost_three_weeks_from_now = now.checked_add_signed(Duration::days(1))
.and_then(|in_2weeks| in_2weeks.checked_add_signed(Duration::weeks(2)))
.and_then(|in_2weeks| in_2weeks.checked_add_signed(Duration::hours(3)))
.and_then(|in_2weeks| in_2weeks.checked_add_signed(Duration::seconds(-4)))
;
match almost_three_weeks_from_now {
Some(x) => println!("{}", x),
None => eprintln!("時間超出范圍"),
}
match now.checked_add_signed(Duration::max_value()) {
Some(x) => println!("{}", x),
None => eprintln!("時間超出范圍,不能計算出太陽系繞銀河系中心一周以上的時間."),
}
}三、時區(qū)轉換
使用 chrono庫的DateTime::from_naive_utc_and_offset 方法將本地時間轉換為 UTC 標準格式。然后使用 offset::FixedOffset 結構體,將 UTC 時間轉換為 UTC+8 和 UTC-2。
use chrono::{DateTime, FixedOffset, Local, Utc};
fn main() {
let local_time = Local::now();
let utc_time = DateTime::<Utc>::from_naive_utc_and_offset(local_time.naive_utc(), Utc);
let china_timezone = FixedOffset::east_opt(8 * 3600);
let rio_timezone = FixedOffset::west_opt(2 * 3600);
println!("本地時間: {}", local_time);
println!("UTC時間: {}", utc_time);
println!(
"北京時間: {}",
utc_time.with_timezone(&china_timezone.unwrap())
);
println!("里約熱內(nèi)盧時間: {}", utc_time.with_timezone(&rio_timezone.unwrap()));
}四、年月日時分秒
獲取當前時間年月日、星期、時分秒,使用chrono庫:
use chrono::{Datelike, Timelike, Local};
fn main() {
let now = Local::now();
let (is_common_era, year) = now.year_ce();
println!(
"當前年月日: {}-{:02}-{:02} {:?} ({})",
year,
now.month(),
now.day(),
now.weekday(),
if is_common_era { "CE" } else { "BCE" }
);
let (is_pm, hour) = now.hour12();
println!(
"當前時分秒: {:02}:{:02}:{:02} {}",
hour,
now.minute(),
now.second(),
if is_pm { "PM" } else { "AM" }
);
}五、時間格式化
時間格式化會用到chrono庫,用format方法進行時間格式化;NaiveDateTime::parse_from_str方法進行字符串轉DateTime,代碼如下:
use chrono::{DateTime, Local, ParseError, NaiveDateTime};
fn main() -> Result<(), ParseError>{
let now: DateTime<Local> = Local::now();
// 時間格式化
let ymdhms = now.format("%Y-%m-%d %H:%M:%S%.3f");
// 字符串轉時間
let no_timezone = NaiveDateTime::parse_from_str("2015-09-05 23:56:04.800", "%Y-%m-%d %H:%M:%S%.3f")?;
println!("當前時間: {}", now);
println!("時間格式化: {}", ymdhms);
println!("字符串轉時間: {}", no_timezone);
Ok(())
}Rust的時間與日期操作就簡單介紹到這里,關注不迷路(*^▽^*)
到此這篇關于Rust操作日期與時間的文章就介紹到這了,更多相關Rust日期與時間內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
rust 如何使用 cargo-nextest 替代 cargo te
cargo-nextest 是新一代的rust測試程序,能夠極大提升測試性能,可以完全替代 cargo test 命令,這篇文章主要介紹了rust 如何使用 cargo-nextest 替代 cargo test,需要的朋友可以參考下2024-05-05
Rust并發(fā)編程之使用消息傳遞進行線程間數(shù)據(jù)共享方式
文章介紹了Rust中的通道(channel)概念,包括通道的基本概念、創(chuàng)建并使用通道、通道與所有權、發(fā)送多個消息以及多發(fā)送端,通道提供了一種線程間安全的通信機制,通過所有權規(guī)則確保數(shù)據(jù)安全,并且支持多生產(chǎn)者單消費者架構2025-02-02

