gpt4 book ai didi

time - 如何将 time::Tm 转换为 u64 以获得 JWT 到期日期

转载 作者:行者123 更新时间:2023-11-29 08:06:17 25 4
gpt4 key购买 nike

我正在使用 jwt crate我想在 Claims 中设置到期日期结构。 exp Registered 中的字段拿了Option<u64> .

我可以通过以下方式检索当前日期并向其添加 1 天:

let mut timer = time::now();
timer = timer + Duration::days(1);

但我不知道如何转换这个 time::Tmu64 .

最佳答案

exp 字段是“NumericDate”类型,根据RFC 7519是“从 1970-01-01T00:00:00Z UTC 到指定的 UTC 日期/时间的秒数,忽略闰秒。

此描述与the to_timespec method相同,在 Tm 的当前时区*中“将时间转换为从 1970 年 1 月 1 日开始的秒数”。

因此:

let mut timer = time::now_utc();
timer = timer + Duration::days(1);
token.claims.reg.exp = Some(timer.to_timespec().sec as u64);

(请注意,虽然 time + duration 从 v0.1.36 开始始终返回 UTC 时间,但有争议的是 a defect 可以在未来修复。为了向前兼容,我使用了 now_utc() 而不是 now()。)

(*: to_timespec 基本上在 POSIX 上调用 gmtime() 并且 POSIX 标准忽略闰秒。在 Windows 上它将结构转换为 FILETIME which again ignores leap seconds 。所以如果您真的关心 27 秒的差异,to_timespec 是安全的。)


如果您正在使用 std::time::SystemTime,同样可以使用

let mut timer = SystemTime::now();
timer += Duration::from_secs(86400);
token.claims.reg.exp = Some(timer.duration_since(UNIX_EPOCH).unwrap().as_secs());

关于time - 如何将 time::Tm 转换为 u64 以获得 JWT 到期日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42627267/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com