当前位置: 首页 > news >正文

【Rust】操作日期与时间

目录

介绍

一、计算耗时

二、时间加减法

三、时区转换

四、年月日时分秒

五、时间格式化


介绍

        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的时间与日期操作就简单介绍到这里,关注不迷路(*^▽^*)

http://www.lryc.cn/news/181520.html

相关文章:

  • blender快捷键
  • java Spring Boot 自动启动热部署 (别再改点东西就要重启啦)
  • TouchGFX之后端通信
  • cesium gltf控制
  • Spring的依赖注入(DI)以及优缺点
  • 【强化学习】05 —— 基于无模型的强化学习(Prediction)
  • 【计算机组成原理】考研真题攻克与重点知识点剖析 - 第 1 篇:计算机系统概述
  • 【Java-LangChain:面向开发者的提示工程-8】聊天机器人
  • 利用t.ppft.interval分别计算T分布置信区间[实例]
  • 软件工程第三周
  • 动态链接那些事
  • 力扣:118. 杨辉三角(Python3)
  • QGIS文章二——DEM高程裁剪和3D地形图
  • 【kubernetes】kubernetes中的StatefulSet使用
  • 创建文件夹
  • 点击router-link时候会发生什么?
  • 【Spring】@Bean方法中存在继承如何分析
  • 【Vim 插件管理器】Vim-plug和Vim-vbundle的区别
  • 电子计算机核心发展(继电器-真空管-晶体管)
  • SDI-12协议与STM32 进行uart通信
  • JS中的强制类型转换
  • WebSocket实战之四WSS配置
  • veImageX 演进之路:Web 图片加载提速50%
  • WebSocket实战之五JSR356
  • flask-sqlalchemy结合Blueprint遇到循环引入问题的解决方案
  • 05_对象性能模式
  • 快速选择排序
  • 国庆中秋特辑(六)大学生常见30道宝藏编程面试题
  • Centos7 安装mysql 8.0.34
  • 如何在 Google Earth 中创建轨迹、路线并制作动画