13个版本
使用旧的Rust 2015
0.8.0 | 2019年5月16日 |
---|---|
0.7.1 | 2018年1月18日 |
0.7.0 | 2017年11月28日 |
0.6.5 | 2016年9月15日 |
0.6.3 | 2016年2月20日 |
在日期和时间类别中排名254
100KB
2K SLoC
沙漏
为Rust编程语言提供时区感知的日期/时间库(文档)
沙漏
提供了对时区、日期时间算术的支持,并处理与时间处理相关的细微差别,如闰秒。
使用方法
在您的Cargo.toml
中添加以下内容:
[dependencies]
hourglass = "0.*"
并将以下内容放在您的crate根目录下:
extern crate hourglass;
概览
时区
由于没有时区的日期时间是模糊的和易出错的,因此沙漏
只公开了一个时区感知的Datetime
。创建一个Timezone
是API的入口点。沙漏
提供了多种创建Timezone
的方法。
use hourglass::Timezone;
let utc = Timezone::utc();
let local = Timezone::local().unwrap();
let paris = Timezone::new("Europe/Paris").unwrap();
let fixed = Timezone::fixed(-5 * 3600);
为特定时区创建的Datetime
可以投影到另一个时区。
use hourglass::Timezone;
let utc = Timezone::utc();
let paris = Timezone::new("Europe/Paris").unwrap();
// Create a `Datetime` corresponding to midnight in Paris timezone...
let t = paris.datetime(2015, 12, 25, 0, 0, 0, 0).unwrap();
// ... and project it into UTC timezone.
let t_utc = t.project(&utc);
assert_eq!(t_utc.date(), (2015, 12, 24));
assert_eq!(t_utc.time(), (23, 0, 0, 0));
算术
使用Deltatime
执行Datetime算术。处理
Deltatime
时可用多个粒度,并将产生不同的结果。
use hourglass::{Timezone, Deltatime};
let utc = Timezone::utc();
let t = utc.datetime(2015, 6, 30, 0, 0, 0, 0).unwrap();
let t_plus_1_day = t + Deltatime::days(1);
let t_plus_86400_sec = t + Deltatime::seconds(86400);
assert_eq!(t_plus_1_day.date(), (2015, 7, 1));
// One leap second was inserted this day.
assert_eq!(t_plus_86400_sec.date(), (2015, 6, 30));
assert_eq!(t_plus_86400_sec.time(), (23, 59, 60, 0));
两个Datetime
也可以进行比较。
use hourglass::{Timezone, Deltatime};
let utc = Timezone::utc();
let t0 = utc.datetime(2015, 6, 30, 0, 0, 0, 0).unwrap();
let t1 = utc.datetime(2015, 7, 1, 0, 0, 0, 0).unwrap();
assert_eq!(t0 < t1, true);
assert_eq!(t0 >= t1, false);
assert_eq!(t1 == t1, true);
assert_eq!(t1 - t0, Deltatime::seconds(86401));
迭代器
沙漏
还提供了用于在固定时间间隔执行循环体执行的Every
迭代器。
use hourglass::{Timezone, Deltatime, Timespec, Every};
let paris = Timezone::new("Europe/Paris").unwrap();
let until = Timespec::now() + Deltatime::seconds(5);
for t in Every::until(Deltatime::seconds(1), until) {
println!("it is {} in Paris", t.to_datetime(&paris).format("%H:%M:%S").unwrap());
}
可以使用Range
迭代器遍历Timespec的范围。
use hourglass::{Deltatime, Timespec, Range};
let now = Timespec::now();
let then = now + Deltatime::minutes(1);
for t in Range::new(now, then, Deltatime::seconds(1)) {
println!("tick {}", t.seconds());
}
依赖项
~1MB
~16K SLoC