如何将DateTime::now()转换为NaiveDateTime?

40

我正在使用 Diesel 和 chrono。在我的模型中,我有一个类型为 NaiveDateTime 的字段,其中包含 now()。然而,NaiveDateTime 没有 now() 或类似的函数,而 DateTime 有:

Utc::now()

如何将 Utc::now() 转换为 NaiveDateTime

1个回答

66

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");
}

6
赞同使用数据库作为时间来源是更好的选择,尤其是在多台机器(拥有不同时间来源)连接到一个数据库的情况下。+1 - Shepmaster
对于那些可能需要本地版本的人来说,它是 Local::now().naive_local() - BinaryButterfly

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接