time::PrimitiveDateTime to u32

Rather simple question.
I have three variables, one for a day, one for a month and one for a year.
I want to, from this, get the UNIX Timestamp (in seconds);
I figured you'd want to construct, with the time crate, a PrimitiveDateTime, though I got stuck at this step.

Here's one way to do this with chrono:

2 Likes

eh, that works. Thanks.

A year, month and day is a civil time. The correct way to get from that to a physical time (like a Unix timestamp) is with a time zone. You can't generally do that with time, but you can select a specific offset from UTC, which may or may not be correct for your circumstance. You can see an example here: PrimitiveDateTime in time - Rust

Or, using Jiff, you can provide a time zone:

use jiff::civil;

fn main() -> anyhow::Result<()> {
    let date = civil::date(2025, 1, 29);
    let timestamp = date.in_tz("US/Eastern")?.timestamp();
    println!(" RFC 3339: {timestamp}");
    println!("Timestamp: {}", timestamp.as_second());

    Ok(())
}

Has this output:

$ cargo -q r
 RFC 3339: 2025-01-29T05:00:00Z
Timestamp: 1738126800
1 Like

time isn't in the standard library. And be careful, that code example is only correct if your date is in UTC, which it may or may not be.

1 Like

:wave: maintainer of time here.

Confirming that as correct. A PrimitiveDateTime does not represent a moment in time as it does not have sufficient information to do so. However, calling .assume_utc() or similar (note: this assumption is not validated) will give you an OffsetDateTime that you can call .unix_timestamp() on. This returns an i64, which is necessary to represent the range of valid values.

2 Likes