我一直在尝试,但很难,因为类型不完全匹配。
我目前的尝试:
use ::time::{PrimitiveDateTime, OffsetDateTime};
use std::time::{UNIX_EPOCH, Duration};
use chrono::{DateTime, Utc, NaiveDateTime};
fn my_func() {
let timestamp:u64 = 30000000 // {integer from http request, representing timestamp in ms since epoch}
let d:SystemTime = UNIX_EPOCH + Duration::from_secs(timestamp/1000);
let datetime:DateTime<Utc> = DateTime::<Utc>::from(d); // ideally want to replace this line with one where I get a DateTime (and not DateTime<Utc>) from the integer.
let created_at:PrimitiveDateTime = PrimitiveDateTime::new(datetime.date_naive(), datetime.time());
}
我的错误消息(编译)如下:
106 | ... = PrimitiveDateTime::new(datetime.date_naive(), datetime.time(...
| ^^^^^^^^^^^^^^^^^^^^^^ --------------------- --------------- expected `Time`, found `NaiveTime`
| |
| expected `Date`, found `NaiveDate`
|
note: associated function defined here
--> /.../time-0.3.23/src/primitive_date_time.rs:92:18
|
92 | pub const fn new(date: ...
| ^^^
我需要使用 PrimitiveDateTime 因为这是时间戳在 psql DB 中的存储方式。
chrono
有一种方法可以将纪元以来的毫秒转换为NaiveDateTime
...但time
没有。
经过大量研究,我发现有一种方法可以将它们转换为
OffsetDateTime
:from_unix_timestamp_nanos()
(只有秒和纳秒的方法,没有毫秒的方法)。但是没有方法可以将 OffsetDateTime
转换为 PrimitiveDateTime
,但是 PrimitiveDateTime::new(dt.date(), dt.time())
似乎可以工作。
所以:
use time::{OffsetDateTime, PrimitiveDateTime};
fn main() {
let timestamp: u64 = 3000000000000; // {integer from http request, representing timestamp in ms since epoch}
let created_at =
OffsetDateTime::from_unix_timestamp_nanos(i128::from(timestamp) * 1_000_000).unwrap();
let created_at = PrimitiveDateTime::new(created_at.date(), created_at.time());
dbg!(created_at);
}