HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustMajor

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howdatetimenaivedatetimenowconvertinto

Problem

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?

Solution

Utc::now() returns a DateTime. You could click into the documentation of DateTime 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");
}

Code Snippets

let naive_date_time = Utc::now().naive_utc();
//! ```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");
}

Context

Stack Overflow Q#48236838, score: 80

Revisions (0)

No revisions yet.