Rust日期與時(shí)間的操作方法
介紹
Rust的時(shí)間操作主要用到chrono庫,接下來我將簡(jiǎn)單選一些常用的操作進(jìn)行介紹,如果想了解更多細(xì)節(jié),請(qǐng)查看官方文檔。
官方文檔:chrono - Rust
Cargo.toml引用:chrono = { version = "0.4", features = ["serde"] }
一、計(jì)算耗時(shí)
Rust標(biāo)準(zhǔn)庫,一般用于計(jì)算變量start和duration之間的程序運(yùn)行時(shí)間,代碼如下:
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!("耗時(shí): {:?}", duration);
}二、時(shí)間加減法
使用到chrono庫的checked_add_signed方法,如果無法計(jì)算出日期和時(shí)間,方法將返回 None。比如當(dāng)前時(shí)間加一天、加兩周、加3小時(shí)再減4秒,代碼如下:
use chrono::{Duration, Local};
fn main() {
// 獲取當(dāng)前時(shí)間
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!("時(shí)間超出范圍"),
}
match now.checked_add_signed(Duration::max_value()) {
Some(x) => println!("{}", x),
None => eprintln!("時(shí)間超出范圍,不能計(jì)算出太陽系繞銀河系中心一周以上的時(shí)間."),
}
}三、時(shí)區(qū)轉(zhuǎn)換
使用 chrono庫的DateTime::from_naive_utc_and_offset 方法將本地時(shí)間轉(zhuǎn)換為 UTC 標(biāo)準(zhǔn)格式。然后使用 offset::FixedOffset 結(jié)構(gòu)體,將 UTC 時(shí)間轉(zhuǎn)換為 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!("本地時(shí)間: {}", local_time);
println!("UTC時(shí)間: {}", utc_time);
println!(
"北京時(shí)間: {}",
utc_time.with_timezone(&china_timezone.unwrap())
);
println!("里約熱內(nèi)盧時(shí)間: {}", utc_time.with_timezone(&rio_timezone.unwrap()));
}四、年月日時(shí)分秒
獲取當(dāng)前時(shí)間年月日、星期、時(shí)分秒,使用chrono庫:
use chrono::{Datelike, Timelike, Local};
fn main() {
let now = Local::now();
let (is_common_era, year) = now.year_ce();
println!(
"當(dāng)前年月日: {}-{:02}-{:02} {:?} ({})",
year,
now.month(),
now.day(),
now.weekday(),
if is_common_era { "CE" } else { "BCE" }
);
let (is_pm, hour) = now.hour12();
println!(
"當(dāng)前時(shí)分秒: {:02}:{:02}:{:02} {}",
hour,
now.minute(),
now.second(),
if is_pm { "PM" } else { "AM" }
);
}五、時(shí)間格式化
時(shí)間格式化會(huì)用到chrono庫,用format方法進(jìn)行時(shí)間格式化;NaiveDateTime::parse_from_str方法進(jìn)行字符串轉(zhuǎn)DateTime,代碼如下:
use chrono::{DateTime, Local, ParseError, NaiveDateTime};
fn main() -> Result<(), ParseError>{
let now: DateTime<Local> = Local::now();
// 時(shí)間格式化
let ymdhms = now.format("%Y-%m-%d %H:%M:%S%.3f");
// 字符串轉(zhuǎn)時(shí)間
let no_timezone = NaiveDateTime::parse_from_str("2015-09-05 23:56:04.800", "%Y-%m-%d %H:%M:%S%.3f")?;
println!("當(dāng)前時(shí)間: {}", now);
println!("時(shí)間格式化: {}", ymdhms);
println!("字符串轉(zhuǎn)時(shí)間: {}", no_timezone);
Ok(())
}Rust的時(shí)間與日期操作就簡(jiǎn)單介紹到這里,關(guān)注不迷路(*^▽^*)
到此這篇關(guān)于Rust操作日期與時(shí)間的文章就介紹到這了,更多相關(guān)Rust日期與時(shí)間內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Rust 的 into_owned() 方法實(shí)例詳解
into_owned是Rust語言中std::borrow::Cow 枚舉的一個(gè)方法,into_owned確保了調(diào)用者獲得數(shù)據(jù)的獨(dú)立所有權(quán),無論Cow之前是引用還是已經(jīng)擁有數(shù)據(jù),本文給大家介紹Rust 的 into_owned() 方法,感興趣的的朋友跟隨小編一起看看吧2024-03-03
rust 如何使用 cargo-nextest 替代 cargo te
cargo-nextest 是新一代的rust測(cè)試程序,能夠極大提升測(cè)試性能,可以完全替代 cargo test 命令,這篇文章主要介紹了rust 如何使用 cargo-nextest 替代 cargo test,需要的朋友可以參考下2024-05-05
Rust并發(fā)編程之使用消息傳遞進(jìn)行線程間數(shù)據(jù)共享方式
Rust中GUI庫egui的簡(jiǎn)單應(yīng)用指南

