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()
}
相关推荐
IT笔记36 分钟前
【Rust】Rust数组和Vec安全读写笔记
笔记·安全·rust
Source.Liu1 小时前
【Chrono库】时间区域(TimeZone)Rust实现详解(src/offset/local/tz_info/timezone.rs)
rust·time
CNRio2 小时前
GitCode CLI:从Python到Rust的重构之旅
python·rust·gitcode
xcLeigh2 小时前
【新】Rust入门:基础语法应用
开发语言·算法·rust
星释2 小时前
Rust 练习册 103:维吉尼亚密码与安全通信
网络·安全·rust
美味小鱼3 小时前
DupFinder:一个用 Rust 编写的高性能重复文件查找工具
开发语言·后端·rust
Source.Liu3 小时前
【Chrono库】 时区转换规则(TransitionRule)实现详解(src/offset/local/tz_info/rule.rs)
rust·time
星释11 小时前
Rust 练习册 100:音乐音阶生成器
开发语言·后端·rust
木易 士心17 小时前
Go、Rust、Kotlin、Python 与 Java 从性能到生态,全面解读五大主流编程语言
java·golang·rust
badmonster018 小时前
AI ETL需要不同的原语:从构建CocoIndex中学到的Rust经验🦀
rust·aigc