introduce
Rust's time operation mainly uses the chrono library. Next, I will briefly select some commonly used operations to introduce them. If you want to know more details, please check the official documentation.
Official document:chrono - Rust
Quote: chrono = { version = "0.4", features = ["serde"] }
1. Calculation time-consuming
Rust standard library, generally used to calculate the program run time between variables start and duration, the code is as follows:
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 = (); println!("time consuming: {:?}", duration); }
2. Time addition and subtraction
Use the checked_add_signed method to the chrono library. If the date and time cannot be calculated, the method will return None. For example, add one day, two weeks, add 3 hours and 4 seconds at the current time. The code is as follows:
use chrono::{Duration, Local}; fn main() { // Get the current time 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!("Time out of range"), } match now.checked_add_signed(Duration::max_value()) { Some(x) => println!("{}", x), None => eprintln!("Time is out of range, and it is impossible to calculate the time it takes for the solar system to orbit the center of the Milky Way more than one week."), } }
3. Time zone conversion
Use the DateTime::from_naive_utc_and_offset method of the chrono library to convert local time to UTC standard format. Then use the offset::FixedOffset structure to convert UTC time to UTC+8 and 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: {}", local_time); println!("UTCtime: {}", utc_time); println!( "北京time: {}", utc_time.with_timezone(&china_timezone.unwrap()) ); println!("里约热内卢time: {}", utc_time.with_timezone(&rio_timezone.unwrap())); }
4. Year, month, day, hour, minute, second
Get the current time, year, month, day, week, hour, minute, and second, and use the chrono library:
use chrono::{Datelike, Timelike, Local}; fn main() { let now = Local::now(); let (is_common_era, year) = now.year_ce(); println!( "Current year, month, day: {}-{:02}-{:02} {:?} ({})", year, (), (), (), if is_common_era { "CE" } else { "BCE" } ); let (is_pm, hour) = now.hour12(); println!( "Current time, minute, and second: {:02}:{:02}:{:02} {}", hour, (), (), if is_pm { "PM" } else { "AM" } ); }
5. Time formatting
Time formatting will use the chrono library, and the format method is used to format the time; NaiveDateTime::parse_from_str method to string to DateTime, the code is as follows:
use chrono::{DateTime, Local, ParseError, NaiveDateTime}; fn main() -> Result<(), ParseError>{ let now: DateTime<Local> = Local::now(); // Time formatting let ymdhms = ("%Y-%m-%d %H:%M:%S%.3f"); // String time let no_timezone = NaiveDateTime::parse_from_str("2015-09-05 23:56:04.800", "%Y-%m-%d %H:%M:%S%.3f")?; println!("Current time: {}", now); println!("Time formatting: {}", ymdhms); println!("String to time: {}", no_timezone); Ok(()) }
This is the brief introduction to Rust's time and date operations. Pay attention to it and don't get lost (*^▽^*)
This is the end of this article about Rust operation date and time. For more related Rust date and time, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!