当前位置: 代码网 > 科技>电脑产品>内存 > 【Rust】操作日期与时间

【Rust】操作日期与时间

2024年07月28日 内存 我要评论
Rust的时间操作主要用到chrono库,接下来我将简单选一些常用的操作进行介绍,如果想了解更多细节,请查看官方文档。

目录

介绍

一、计算耗时

二、时间加减法

三、时区转换

四、年月日时分秒

五、时间格式化


介绍

        rust的时间操作主要用到chrono库,接下来我将简单选一些常用的操作进行介绍,如果想了解更多细节,请查看官方文档。

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

三、时区转换

        使用 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!("里约热内卢时间: {}", 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的时间与日期操作就简单介绍到这里,关注不迷路(*^▽^*)

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com