How to convert DateTime::now() into NaiveDateTime?

Utc::now() returns a DateTime<Utc>. You could click into the documentation of DateTime<T> and search for NaiveDateTime. You should find that there are two methods that will return a NaiveDateTime:

fn naive_utc(&self) -> NaiveDateTime

  Returns a view to the naive UTC datetime.

fn naive_local(&self) -> NaiveDateTime

  Returns a view to the naive local datetime.

For instance, if you need the timestamp in UTC:

let naive_date_time = Utc::now().naive_utc();

Note that since you are using diesel, you could use diesel::dsl::now instead, which will evaluate to CURRENT_TIMESTAMP on the SQL side.

//! ```cargo
//! [dependencies]
//! diesel = { version = "1", features = ["sqlite"] }
//! ```

#[macro_use]
extern crate diesel;

use diesel::prelude::*;
use diesel::dsl;

table! {
    posts (id) {
        id -> Integer,
        content -> Text,
        published -> Timestamp,
    }
}

fn main() {
    let conn = SqliteConnection::establish("test.db")
        .expect("Cannot open database");

    diesel::insert_into(posts::table)
        .values((
            posts::content.eq("hello"),
            posts::published.eq(dsl::now),  // <------------------
        ))
        .execute(&conn)
        .expect("Insertion failed");
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)