• 【Rust】操作日期与时间


    目录

    介绍

    一、计算耗时

    二、时间加减法

    三、时区转换

    四、年月日时分秒

    五、时间格式化


    介绍

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

            官方文档:chrono - Rust

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

    一、计算耗时

            Rust标准库,一般用于计算变量start和duration之间的程序运行时间,代码如下:

    1. use std::time::{Duration, Instant};
    2. use std::thread;
    3. fn expensive_function(seconds:u64) {
    4. thread::sleep(Duration::from_secs(seconds));
    5. }
    6. fn main() {
    7. cost();
    8. }
    9. fn cost(){
    10. let start = Instant::now();
    11. expensive_function(2);
    12. let duration = start.elapsed();
    13. println!("耗时: {:?}", duration);
    14. }

    二、时间加减法

            使用到chrono库的checked_add_signed方法,如果无法计算出日期和时间,方法将返回 None。比如当前时间加一天、加两周、加3小时再减4秒,代码如下:

    1. use chrono::{Duration, Local};
    2. fn main() {
    3. // 获取当前时间
    4. let now = Local::now();
    5. println!("{}", now);
    6. let almost_three_weeks_from_now = now.checked_add_signed(Duration::days(1))
    7. .and_then(|in_2weeks| in_2weeks.checked_add_signed(Duration::weeks(2)))
    8. .and_then(|in_2weeks| in_2weeks.checked_add_signed(Duration::hours(3)))
    9. .and_then(|in_2weeks| in_2weeks.checked_add_signed(Duration::seconds(-4)))
    10. ;
    11. match almost_three_weeks_from_now {
    12. Some(x) => println!("{}", x),
    13. None => eprintln!("时间超出范围"),
    14. }
    15. match now.checked_add_signed(Duration::max_value()) {
    16. Some(x) => println!("{}", x),
    17. None => eprintln!("时间超出范围,不能计算出太阳系绕银河系中心一周以上的时间."),
    18. }
    19. }

    三、时区转换

            使用 chrono库的DateTime::from_naive_utc_and_offset 方法将本地时间转换为 UTC 标准格式。然后使用 offset::FixedOffset 结构体,将 UTC 时间转换为 UTC+8 和 UTC-2。

    1. use chrono::{DateTime, FixedOffset, Local, Utc};
    2. fn main() {
    3. let local_time = Local::now();
    4. let utc_time = DateTime::::from_naive_utc_and_offset(local_time.naive_utc(), Utc);
    5. let china_timezone = FixedOffset::east_opt(8 * 3600);
    6. let rio_timezone = FixedOffset::west_opt(2 * 3600);
    7. println!("本地时间: {}", local_time);
    8. println!("UTC时间: {}", utc_time);
    9. println!(
    10. "北京时间: {}",
    11. utc_time.with_timezone(&china_timezone.unwrap())
    12. );
    13. println!("里约热内卢时间: {}", utc_time.with_timezone(&rio_timezone.unwrap()));
    14. }

    四、年月日时分秒

            获取当前时间年月日、星期、时分秒,使用chrono库:

    1. use chrono::{Datelike, Timelike, Local};
    2. fn main() {
    3. let now = Local::now();
    4. let (is_common_era, year) = now.year_ce();
    5. println!(
    6. "当前年月日: {}-{:02}-{:02} {:?} ({})",
    7. year,
    8. now.month(),
    9. now.day(),
    10. now.weekday(),
    11. if is_common_era { "CE" } else { "BCE" }
    12. );
    13. let (is_pm, hour) = now.hour12();
    14. println!(
    15. "当前时分秒: {:02}:{:02}:{:02} {}",
    16. hour,
    17. now.minute(),
    18. now.second(),
    19. if is_pm { "PM" } else { "AM" }
    20. );
    21. }

    五、时间格式化

            时间格式化会用到chrono库,用format方法进行时间格式化;NaiveDateTime::parse_from_str方法进行字符串转DateTime,代码如下:

    1. use chrono::{DateTime, Local, ParseError, NaiveDateTime};
    2. fn main() -> Result<(), ParseError>{
    3. let now: DateTime = Local::now();
    4. // 时间格式化
    5. let ymdhms = now.format("%Y-%m-%d %H:%M:%S%.3f");
    6. // 字符串转时间
    7. let no_timezone = NaiveDateTime::parse_from_str("2015-09-05 23:56:04.800", "%Y-%m-%d %H:%M:%S%.3f")?;
    8. println!("当前时间: {}", now);
    9. println!("时间格式化: {}", ymdhms);
    10. println!("字符串转时间: {}", no_timezone);
    11. Ok(())
    12. }

            Rust的时间与日期操作就简单介绍到这里,关注不迷路(*^▽^*)

  • 相关阅读:
    【.Net8教程】(二)原始字符串字面量
    OpenMV:22电机扩展板控制直流电机
    剑指JUC原理-15.ThreadLocal
    LeetCode-102.题: 二叉树的层序遍历(原创)
    csp初赛总结 & 那些年编程走过的坑 & 初高中信竞常考语法算法点
    分页功能实现
    Mysql学习之——增删改查语句
    springboot做系统一定要前后端吗?只有前端或者只有后端可以吗?
    终于结束的起点(滚动数组,记忆化搜索)
    计算机系统大作业:Hello的一生
  • 原文地址:https://blog.csdn.net/xian0710830114/article/details/133305490