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

标签 datetime rust timestamp

我正在使用 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/

相关文章:

sql-server - 计算发货时间超过 X 天的订单百分比的更好方法?

rust - 如何使用 Rust 迭代器获得多个 `if let`?

rust - 我如何将 stdout 输出到以 Rust 语言执行 std::process::Command 的终端

Outlook 2007 延迟电子邮件时间戳显示创建时间

ruby-on-rails - 在 Ruby 中将 UTC 时间戳转换为 ISO 8601

php - 为什么在尝试获取 2 个 DateTime 对象的 diff() 时出现 fatal error

javascript - moment() 获取今天的午夜日期

java - 在 JAVA 中将 Json 日期时间转换为字符串

generics - Rust 类型级乘法

cassandra - 如何在使用命令行时使用 CQL 获取当前时间戳?