rust - 常用时间处理

本文提供了一些常用的时间处理函数。

复制代码
use chrono::prelude::*;
use std::time::SystemTime;

const DATETIME_FORMAT: &str = "%Y-%m-%d %H:%M:%S";

将当前时间转换为UTC时区的字符串格式

rust 复制代码
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 转换为指定格式的字符串

rust 复制代码
/// 将 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时间戳

rust 复制代码
/// 将 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()
}

获得当前时间戳

rust 复制代码
/// 获得当前时间戳
pub fn now_to_seconds() -> i64 {
    let now = Local::now();
    now.timestamp()
}

时间字符串转换为 SystemTime

rust 复制代码
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()
}
相关推荐
受之以蒙2 小时前
赋能 AI 与具身智能:Rust ndarray 构建安全高效的数据底座
人工智能·笔记·rust
Pomelo_刘金2 小时前
Rust : 新版本 1.90.0
rust
songroom5 小时前
Rust: 量化策略回测与简易线程池构建、子线程执行观测
开发语言·后端·rust
资深web全栈开发5 小时前
二分搜索中 `right = mid` 而非 `right = mid + 1` 的解释
算法·rust·二分搜索
Pomelo_刘金5 小时前
Rust : 新版本 1.89.0
rust
Pomelo_刘金5 小时前
Rust : Trusted Publishing(受信发布)
rust
Pomelo_刘金5 小时前
Rust :裸函数 naked functions
rust·嵌入式
猫头虎9 小时前
Rust评测案例:Rust、Java、Python、Go、C++ 实现五大排序算法的执行时间效率比较(基于 OnlineGDB 平台)
java·开发语言·c++·python·golang·rust·排序算法
ftpeak9 小时前
Rust 嵌入式开发的经验之谈
开发语言·后端·rust
已黑化的小白20 小时前
Rust 的所有权系统,是一场对“共享即混乱”的编程革命
开发语言·后端·rust