API 指南
结构体概览
| 结构体 | 说明 |
|---|---|
timestamp | 时间戳对象,存储秒/微秒/纳秒三种精度的时间戳 |
time | 日期时间对象,存储年/月/日/时/分/秒 |
timestamp
定义
rust
#[derive(Default)]
struct timestamp {
timestamp_s: u64,
timestamp_ms: u128,
timestamp_ns: u128,
}方法
new() -> Self
创建一个默认的 timestamp 实例(所有字段为 0)。
rust
let t = timestamp::new();get_timestamp(self) -> Self
获取当前时间戳,填充秒、微秒、纳秒字段。消耗 self 并返回填充后的新实例。
rust
let t = timestamp::new().get_timestamp();
println!("秒: {}", t.timestamp_s);
println!("微秒: {}", t.timestamp_ms);
println!("纳秒: {}", t.timestamp_ns);内部实现:通过 SystemTime::now().duration_since(UNIX_EPOCH) 获取当前时间距 UNIX 纪元的时间差,分别提取 as_secs()、as_micros()、as_nanos()。
time
定义
rust
#[derive(Default)]
struct time {
year: i32,
mouth: i8,
day: i8,
hour: i8,
minute: i8,
secend: i8,
}方法
new() -> Self
创建一个默认的 time 实例(所有字段为 0)。
rust
let t = time::new();is_leap_year(&self) -> bool
判断当前实例的 year 字段是否为闰年。
闰年规则:
- 能被 400 整除的是闰年
- 能被 100 整除但不能被 400 整除的不是闰年
- 能被 4 整除但不能被 100 整除的是闰年
rust
let mut t = time::new();
t.year = 2024;
assert!(t.is_leap_year());get_time(self) -> Self
获取当前 UTC+8 日期时间,填充年、月、日、时、分、秒字段。消耗 self 并返回填充后的新实例。
rust
let dt = time::new().get_time();
println!("{}-{}-{} {}:{}:{}", dt.year, dt.mouth, dt.day, dt.hour, dt.minute, dt.secend);转换逻辑:
- 先获取当前时间戳(秒)
- 加上 8 小时偏移(UTC+8)
- 从 1970 年开始逐年推算年份
- 根据闰年/平年确定每月天数,逐月推算月份和日期
- 计算时、分、秒
注意事项
- 时区固定为 UTC+8:
get_time()内部硬编码了+ 8 * 3600秒的偏移。 - 构建者模式:
get_timestamp()和get_time()都消耗self,返回新的实例,不支持原地修改。 - 默认值:两个结构体都实现了
Default,new()创建的实例字段全为零值。