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()
}
相关推荐
星栈9 小时前
10 分钟跑起第一个 Dioxus 应用:`dx` CLI、`rsx!` 和热更新好不好用
前端·rust·前端框架
望眼欲穿的程序猿14 小时前
读取芯片内部温度传感器
嵌入式硬件·rust
望眼欲穿的程序猿14 小时前
ADC 模拟电压采集
嵌入式硬件·rust
codexu_46122918715 小时前
NoteGen 里一条记录如何变成 Markdown
前端·笔记·rust·tauri
Rust研习社15 小时前
Rust 错误处理的黄金搭档:一个定义错误,一个传播错误
后端·rust·编程语言
techdashen16 小时前
绕过系统 ICMP:用 rawsock、Npcap 和 WMI 找到默认网卡
开发语言·arm开发·rust
小二·16 小时前
Rust 后端实战:高性能 Web 服务开发全链路
开发语言·前端·rust
island131416 小时前
【开源软件移植】把 RustDesk 的 Rust 核心搬到 HarmonyOS PC:一次 Native HAR 迁移实战记录
开发语言·rust·harmonyos
小二·17 小时前
Rust 爬虫与数据处理实战:大规模并发抓取 + 流式处理
开发语言·爬虫·rust
techdashen17 小时前
绕过 WMI:用 Rust 绑定 Win32 变长结构体和 UTF-16 字符串
开发语言·后端·rust