如何将DateTime::now()转换为DateTime?
我用的是柴油机和chrono。在我的模型中,我有一个类型为如何将DateTime::now()转换为DateTime?,datetime,rust,timestamp,Datetime,Rust,Timestamp,我用的是柴油机和chrono。在我的模型中,我有一个类型为NaiveDateTime的字段,其中包含now()。但是,NaiveDateTime没有函数now()或类似的函数,而DateTime有: Utc::now() 如何将Utc::now()转换为NaiveDateTime?Utc::now()返回一个DateTime。您可以单击并搜索NaiveDateTime。您应该发现有两种方法将返回NaiveDateTime: fn naive\u utc(&self)->NaiveDateTim
NaiveDateTime
的字段,其中包含now()
。但是,NaiveDateTime
没有函数now()
或类似的函数,而DateTime
有:
Utc::now()
如何将Utc::now()
转换为NaiveDateTime
?Utc::now()
返回一个DateTime
。您可以单击并搜索NaiveDateTime
。您应该发现有两种方法将返回NaiveDateTime
:
fn naive\u utc(&self)->NaiveDateTime
返回原始UTC日期时间的视图
fn naiver\u local(&self)->NaiveDateTime
返回原始本地日期时间的视图
例如,如果您需要UTC时间戳:
let naive_date_time = Utc::now().naive_utc();
请注意,由于您使用的是
diesel
,因此可以改用,它将在SQL端计算为CURRENT\u 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");
}
/```货物
//! [依赖关系]
//! diesel={version=“1”,features=[“sqlite”]}
//! ```
#[宏_使用]
外部板条箱柴油机;
使用柴油机::前奏::*;
使用柴油机::dsl;
桌子{
职位(id){
id->Integer,
内容->文本,
已发布->时间戳,
}
}
fn main(){
让conn=SqliteConnection::build(“test.db”)
.expect(“无法打开数据库”);
diesel::将_插入(posts::表格)
.价值观((
posts::content.eq(“你好”),
posts::published.eq(dsl::now),//+1指出使用数据库作为时间源是更好的主意,特别是在多台机器(具有不同的时间源)连接到一个数据库的情况下。