7 个版本 (1 个稳定版)
1.0.0 | 2024年4月5日 |
---|---|
0.6.0 | 2023年7月25日 |
0.4.1 | 2022年5月25日 |
0.3.0 | 2022年4月11日 |
0.1.0 | 2021年9月10日 |
#86 在 日期和时间 分类中
每月116 次下载
被 4 个工具包 使用(2 个直接使用)
19KB
334 行
unix-ts: Rust 的可转换 Unix 时间戳库
unix-ts 是一个处理时间戳的库。它支持轻量级创建和时间戳操作。
目标是作为粘合库,可以接受一个时间戳并将其转换为所需的任何其他格式。
用法
像往常一样将工具包添加到您的 Cargo.toml
文件中
[dependencies]
unix-ts = "1"
您可以使用 ts!
宏创建时间戳,该宏接受 Unix 时间戳作为参数
use unix_ts::ts;
// The argument is the number of seconds since the Unix epoch.
let t = ts!(1335020400);
// Fractional seconds are also allowed.
let t2 = ts!(1335020400.25);
对于整秒时间戳,您也可以使用 from
方法
use unix_ts::Timestamp;
let t = Timestamp::from(1335020400);
对于毫秒、微秒或纳秒,有特定的 from
方法可用
use unix_ts::Timestamp;
let t = Timestamp::from_nanos(1335020400_000_000_000i64);
最后,new
方法接受 seconds
和 nanos
。虽然这通常不如宏方便,因为您必须自己将分数秒转换为纳秒。
读取时间戳
有三种方法可用于读取时间戳
seconds() -> i64
:返回时间戳的整秒值。at_precision(e) -> i128
:以比秒更高的精度返回时间戳作为整数。值e
表示 10 的幂;因此,at_precision(3)
会返回毫秒值。subsec(e) -> u32
:返回给定精度的子秒值。值e
表示 10 的幂;因此,subsec(3)
会返回毫秒级的子秒值。
转换时间戳
当前可以将时间戳转换为整数(会丢失小数部分),或者转换为 std::time::Duration
。这是通过实现 Rust 的 From
特性来完成的(因此您可以使用 from
或 into
方法)。