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 小时前
std1.97.1——fmt模块总览
rust
SomeB1oody3 小时前
【RustyML入门】5.3. 聚类指标
开发语言·后端·机器学习·rust·教程
雾沉川4 小时前
Rust IDE 选型:除 VS Code 之外,RustRover 非商业场景可免费使用
ide·vscode·rust
程序员爱钓鱼4 小时前
Go 编程实战:Map——使用 Key-Value 管理键值数据
后端·rust·go
程序员爱钓鱼5 小时前
Rust Trait Object详解:dyn Trait与动态分发
后端·面试·rust
蒜香可达鸭18 小时前
Grok-build: Rust 工程实践分析
rust
SomeB1oody1 天前
【RustyML入门】5.2. 分类指标
开发语言·后端·机器学习·rust·教程
星栈1 天前
被 Rust async 纠正的三个异步认知
前端·后端·rust
smallswan1 天前
《Rust七十二变》开源了
开发语言·后端·rust·ai编程
深海呐1 天前
Rust 语言完整解读
java·开发语言·rust