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()
}
相关推荐
古城小栈5 小时前
从 cargo-whero 库中,找到提升 rust 的契机
开发语言·后端·rust
techdashen10 小时前
Cloudflare 为何抛弃 NGINX,用 Rust 自研了一个代理
运维·nginx·rust
Mr.Rice.Fool13 小时前
rust面试经验1
后端·面试·职场和发展·rust
本地化文档14 小时前
rust-nomicon-l10n
rust·github·gitcode
代码羊羊14 小时前
Rust 格式化输出完全攻略:从入门到精通
开发语言·后端·rust
Rust研习社14 小时前
Rust + PostgreSQL 极简技术栈应用开发
开发语言·数据库·后端·http·postgresql·rust
古城小栈16 小时前
rust 亿级并发模型,实践完成
开发语言·网络·rust
qcx2316 小时前
Warp源码深度解析(一):GPU加速+AI Agent的下一代终端架构全景
人工智能·架构·rust
暮色念了红尘17 小时前
CC Switch — Ubuntu 20.04 可用版本
ubuntu·ai·rust·ubuntu 20.04·vibe coding·cc swich