Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm using Diesel and chrono. In my model I have a field of type NaiveDateTime which contains the now(). However, NaiveDateTime doesn't have the function now() or a similar one whereas DateTime does:

Utc::now()

How can I convert Utc::now() into NaiveDateTime?

like image 705
Kurama Avatar asked Jan 13 '18 04:01

Kurama


1 Answers

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");
}
like image 96
kennytm Avatar answered Nov 10 '22 14:11

kennytm