我正在使用 Diesel 和 chrono。在我的模型中,我有一个类型为 NaiveDateTime
的字段,其中包含 now()
。然而,NaiveDateTime
没有 now()
或类似的函数,而 DateTime
有:
Utc::now()
如何将 Utc::now()
转换为 NaiveDateTime
?
Utc::now()
返回一个 DateTime<Utc>
。您可以点击 DateTime<T>
的文档 并搜索 NaiveDateTime
,您将找到两个方法返回一个 NaiveDateTime
:
fn naive_utc(&self) -> NaiveDateTime
返回一个视图到纯UTC日期时间。
fn naive_local(&self) -> NaiveDateTime
返回一个视图到本地纯日期时间。
例如,如果需要UTC时间戳:
let naive_date_time = Utc::now().naive_utc();
请注意,因为您正在使用diesel
,所以可以使用diesel::dsl::now
替代,它将在SQL端求值为CURRENT_TIMESTAMP
。//! ```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");
}
Local::now().naive_local()
。 - BinaryButterfly