2

I'm using the jwt crate and I want to set the expiration date in the Claims struct. The exp field in Registered took a Option<u64>.

I can retrieve the current date and add 1 day to it by doing:

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

but I don't see how to convert this time::Tm to a u64.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
NotBad4U
  • 1,502
  • 1
  • 16
  • 23

1 Answers1

3

The exp field is of "NumericDate" type, which according to RFC 7519 is "number of seconds from 1970-01-01T00:00:00Z UTC until the specified UTC date/time, ignoring leap seconds."

This description is the same as the to_timespec method, which "Convert time to the seconds from January 1, 1970" in the Tm's current timezone*.

Thus:

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

(Note that while time + duration always return UTC time as of v0.1.36, it is arguably a defect that could be fixed in a future. To be forward-compatible, I used now_utc() instead of now().)

(*: to_timespec basically calls gmtime() on POSIX and the POSIX standard ignores leap seconds. On Windows it converts the structure to a FILETIME which again ignores leap seconds. So to_timespec is safe to use if you really care about the 27-second difference.)


If you are using std::time::SystemTime, the same can be obtained using

let mut timer = SystemTime::now();
timer += Duration::from_secs(86400);
token.claims.reg.exp = Some(timer.duration_since(UNIX_EPOCH).unwrap().as_secs());
Community
  • 1
  • 1
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005