Skip to content

Instantly share code, notes, and snippets.

@samao
Created May 11, 2024 09:58
Show Gist options
  • Save samao/b94fa5a12c2bce5a0028ebb1c8c6a94f to your computer and use it in GitHub Desktop.
Save samao/b94fa5a12c2bce5a0028ebb1c8c6a94f to your computer and use it in GitHub Desktop.
Rust Chrono (时间处理)
use chrono::{DateTime, Datelike, Local, TimeDelta};
use std::{error::Error, thread::sleep, time::Duration};
fn main() -> Result<(), Box<dyn Error>> {
println!("{:#X}", 250);
let dt = Local::now();
println!("now: {}", dt.format("%Y/%m/%d %H:%M %A"));
let dt = match dt.checked_add_signed(TimeDelta::days(66)) {
Some(d) => d,
_ => panic!("error days"),
};
println!("after move 66 days: {}, {}", dt.format("%Y/%m/%d %H:%M %A"), dt.format("%Y-%m-%d"));
let next = match DateTime::parse_from_str("2025-11-01 00:00 +0800", "%Y-%m-%d %H:%M %z") {
Ok(d) => d.with_timezone(&dt.timezone()),
Err(e) => panic!("error dist time {}", e),
};
println!("next apply timezone: {}", next.format("%Y/%m/%d %H:%M %A"));
println!("UNIX TIME: {}", next.format("%s"));
println!(
"到 {} 还有天数:{} 当天应该是星期:{}",
next.format("%Y/%m/%d %H:%M %A %:::z"),
next.signed_duration_since(dt).num_days(),
next.weekday()
);
println!(
"straightly {}",
match DateTime::parse_from_str("1738339200", "%s") {
Ok(d) => d.signed_duration_since(Local::now()).num_days(),
_ => -1,
}
);
println!("{} /= {:?}", Local::now(), Local::now().date_naive());
let before = Local::now();
sleep(Duration::from_secs(5));
let after = Local::now();
println!("<{}> compare with <{}> is {:?}", before.naive_local(), after.naive_local(), before.cmp(&after));
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment