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
?
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With