我正在使用 Diesel 和 chrono。在我的模型中,我有一个 NaiveDateTime
类型的字段,其中包含 now()
。但是,NaiveDateTime
没有函数 now()
或类似函数,而 DateTime
有:
Utc::now()
如何将 Utc::now()
转换为 NaiveDateTime
?
最佳答案
Utc::now()
返回 DateTime<Utc>
.您可以点击进入 documentation of DateTime<T>
并搜索 NaiveDateTime
.您应该会发现有两种方法会返回 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.
例如,如果您需要 UTC 时间戳:
let naive_date_time = Utc::now().naive_utc();
请注意,因为您使用的是 diesel
, 你可以使用 diesel::dsl::now
相反,它将评估为 CURRENT_TIMESTAMP
在 SQL 方面。
//! ```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");
}
关于datetime - 如何将 DateTime::now() 转换为 NaiveDateTime?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48236838/