Search code examples
rusttimerust-sqlx

Rust create PrimitiveDateTime with now as value and time as crate


I am using the crate time, and I want to create a UTC datetime with now as reference (like "take machine time"). I can do that with OffsetDateTime and now_utc() constructor. but I want a primitive datetime cause I use sqlx and the database type is TIMESTAMP. (postgres).

And PrimitiveDateTime does not implement constructor with machine time.

So I have try to convert my OffsetDateTime into a PrimitiveDateTime and I didn't find the way. And the from / into trait is not implemented between those two type, also OffsetDateTime does not have a method to return a PrimitiveDateTime and offset on the side. The only way I see is to get the calendar date and the time and to rebuild the PrimitiveDateTime on another side.

This solution is really not ideal. that's why I come here.

I want to do

let now = PrimitiveDateTime::now()

or

let now: PrimitiveDatetime = OffsetDateTime::now_utc().as_primitive_utc()

or

let (datetime, _offset) = my_offset_datetime.to_primitive()

Solution

  • I believe the way to do this is like so:

    let now_odt = OffsetDateTime::now_utc();
    let now_pdt = PrimitiveDateTime::new(now_odt.date(), now_odt.time());
    

    That being said, there's already an implementation to use OffsetDateTime with PostgreSQL via sqlx.