【Rust】Operation date and time

Table of contents

introduce

1. Calculation time

2. Time addition and subtraction

3. Time zone conversion

4. Year, month, day, hour, minute and second

5. Time formatting


introduce

        Rust's time operations mainly use the chrono library. Next, I will briefly select some commonly used operations to introduce. If you want to know more details, please check the official documentation.

        Official documentation: chrono - Rust

        Cargo.toml引用:chrono = { version = "0.4", features = ["serde"] }

1. Calculation time

        The Rust standard library is generally used to calculate the program running 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 = start.elapsed();
    println!("耗时: {:?}", duration);
}

2. Time addition and subtraction

        Use the checked_add_signed method of the chrono library. If the date and time cannot be calculated, the method will return None. For example, add one day to the current time, add two weeks, add 3 hours and then subtract 4 seconds. The code is as follows:

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!("时间超出范围,不能计算出太阳系绕银河系中心一周以上的时间."),
    }
}

3. Time zone conversion

        Use the DateTime::from_naive_utc_and_offset method of the chrono library to convert the local time to the UTC standard format. Then use the offset::FixedOffset structure to convert the 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);
    println!("UTC时间: {}", utc_time);
    println!(
        "北京时间: {}",
        utc_time.with_timezone(&china_timezone.unwrap())
    );
    println!("里约热内卢时间: {}", utc_time.with_timezone(&rio_timezone.unwrap()));
}

4. Year, month, day, hour, minute and second

        To get the current time year, month, day, week, hour, minute and second, use the chrono library:

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" }
    );
}

5. Time formatting

        Time formatting will use the chrono library, using the format method to format the time; the NaiveDateTime::parse_from_str method to convert strings to DateTime, the code is as follows:

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(())
}

        This is a brief introduction to Rust’s time and date operations, so pay attention and don’t get lost (*^▽^*)

Guess you like

Origin blog.csdn.net/xian0710830114/article/details/133305490