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()
}
相关推荐
Pomelo_刘金7 小时前
用 DDD 把「闹钟」需求一点点捏出来
架构·rust·领域驱动设计
Pomelo_刘金8 小时前
Clean Architecture 整洁架构:借一只闹钟讲明白「整洁架构」的来龙去脉
后端·架构·rust
a cool fish(无名)18 小时前
rust-方法语法
开发语言·后端·rust
a cool fish(无名)1 天前
rust-参考与借用
java·前端·rust
叶 落1 天前
[Rust 基础课程]猜数字游戏-获取用户输入并打印
rust·rust基础
RustFS2 天前
RustFS 如何修改默认密码?
rust
景天科技苑2 天前
【Rust线程池】如何构建Rust线程池、Rayon线程池用法详细解析
开发语言·后端·rust·线程池·rayon·rust线程池·rayon线程池
该用户已不存在3 天前
Zig想要取代Go和Rust,它有资格吗
前端·后端·rust
用户1774125612443 天前
不懂装懂的AI,折了程序员的阳寿
rust
量子位3 天前
vivo自研蓝河操作系统内核开源!Rust开发新机遇来了
rust·ai编程