How to assign to a new variable the current time using time::PrimitiveDateTime type?

Viewed 38

I'm using time::PrimitiveDateTime and I would like to create a new var with the current time but I cannot find how. Isn't there something like now()?

What about Instant::now()?

Example:

pub struct Player {
  updated_at: Option<PrimitiveDateTime>
}

impl Player {
    pub fn set_updated_at(&mut self) {
        let now = Instant::now();

        self.updated_at = Some(time::PrimitiveDateTime::from(now));
    }

But obviously this doesn't work:

mismatched types
expected struct `time::PrimitiveDateTime`, found struct `time::Instant` rustc E0308
2 Answers

The best way is probably to use PrimitiveDateTime::new with OffsetDateTime::now_(utc|local):

pub struct Player {
  updated_at: Option<PrimitiveDateTime>
}

impl Player {
    pub fn set_updated_at(&mut self) {
        let now = OffsetDateTime::now_utc();

        self.updated_at = Some(PrimitiveDateTime::new(now.date(), now.time()));
    }
}

As per the latest version, OffsetDateTime will have two now-style methods. One for UTC, one for the local time.

If for whatever reason you want a PrimitiveDateTime you can then of course extract the date info from the OffsetDateTime and use those as arguments in the PrimitiveDateTime::new() method.

Related