我正在使用jwt crate,我想在Claims
结构中设置过期日期。 Registered
中的exp
字段占用Option<u64>
。
我可以通过执行以下操作来检索当前日期并添加1天:
let mut timer = time::now();
timer = timer + Duration::days(1);
但我不知道如何将此time::Tm
转换为u64
。
答案 0 :(得分:3)
exp
字段属于“NumericDate”类型,根据RFC 7519是“从1970-01-01T00:00:00Z UTC到指定的UTC日期的秒数/时间,忽略闰秒。“
此描述与the to_timespec
method相同,其中“将时间转换为1970年1月1日的秒数”在Tm的当前时区*。
因此:
let mut timer = time::now_utc();
timer = timer + Duration::days(1);
token.claims.reg.exp = Some(timer.to_timespec().sec as u64);
(请注意,虽然time + duration
始终返回UTC时间v0.1.36,但可以说a defect可以在将来修复。为了向前兼容,我使用了{{1}而不是now_utc()
。)
(*:now()
基本上在POSIX上调用to_timespec
,而POSIX标准忽略了闰秒。在Windows上,它将结构转换为FILETIME which again ignores leap seconds。所以gmtime()
是如果你真的关心27秒的差异,可以安全使用。)
如果您使用的是to_timespec
,则可以使用
std::time::SystemTime