rust-常用时间处理
- IT业界
- 2025-07-22 02:54:01

本文提供了一些常用的时间处理函数。
use chrono::prelude::*; use std::time::SystemTime; const DATETIME_FORMAT: &str = "%Y-%m-%d %H:%M:%S"; 将当前时间转换为UTC时区的字符串格式 pub fn format_datetime() -> String { let now = Utc::now(); return now.format("%Y-%m-%d %H:%M:%S").to_string(); } pub fn format_date() -> String { let now = Utc::now(); return now.format("%Y-%m-%d").to_string(); } 将 SystemTime 转换为指定格式的字符串 /// 将 SystemTime 转换为字符串格式 pub fn format_system_time(st: SystemTime) -> String { // 获得本机时间 let local_datetime: DateTime<Local> = st.clone().into(); // 将本机时间格式化为字符串 local_datetime.format(DATETIME_FORMAT).to_string() } 将 SystemTime 转换为UNIX时间戳 /// 将 SystemTime 转换为UNIX时间戳的秒表示 pub fn to_seconds(st: SystemTime) -> i64 { let local_datetime: DateTime<Local> = st.clone().into(); local_datetime.timestamp() } /// 将 SystemTime 转换为UNIX时间戳的毫秒表示 pub fn to_mill_seconds(st: SystemTime) -> i64 { let local_datetime: DateTime<Local> = st.clone().into(); local_datetime.timestamp_millis() } 获得当前时间戳 /// 获得当前时间戳 pub fn now_to_seconds() -> i64 { let now = Local::now(); now.timestamp() } 时间字符串转换为 SystemTime pub fn to_system_time(datetime_str: &str) -> SystemTime { let no_timezone = NaiveDateTime::parse_from_str(datetime_str, DATETIME_FORMAT).unwrap(); Local.from_local_datetime(&no_timezone).unwrap().into() }rust-常用时间处理由讯客互联IT业界栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“rust-常用时间处理”