我似乎无法弄清楚如何使用 Rust 处理 Unix 时间戳chrono。
我有以下代码,但是naive和 因此datetime变量不正确:
use chrono::{Utc, DateTime, NaiveDateTime};\n\nfn main() {\n println!("Hello, world!");\n\n let timestamp = "1627127393230".parse::<i64>().unwrap();\n let naive = NaiveDateTime::from_timestamp(timestamp, 0);\n let datetime: DateTime<Utc> = DateTime::from_utc(naive, Utc);\n\n println!("timestamp: {}", timestamp);\n println!("naive: {}", naive);\n println!("datetime: {}", datetime);\n}\n\nRun Code Online (Sandbox Code Playgroud)\n输出:
\nuse chrono::{Utc, DateTime, NaiveDateTime};\n\nfn main() {\n println!("Hello, world!");\n\n let timestamp = "1627127393230".parse::<i64>().unwrap();\n let naive = NaiveDateTime::from_timestamp(timestamp, 0);\n let datetime: DateTime<Utc> = DateTime::from_utc(naive, Utc);\n\n println!("timestamp: {}", timestamp);\n println!("naive: {}", naive);\n println!("datetime: {}", datetime);\n}\n\nRun Code Online (Sandbox Code Playgroud)\n当正确的日期时间1627127393230是:
GMT: Saturday, July 24, 2021 11:49:53.230 AM
有人可以告诉我我在这里缺少什么吗?
\n最终解决方案:
\nuse chrono::{DateTime, Utc, NaiveDateTime};\n\npub fn convert(timestamp: i64) -> DateTime<Utc> {\n let naive = NaiveDateTime::from_timestamp_opt(timestamp / 1000, (timestamp % 1000) as u32 * 1_000_000).unwrap();\n DateTime::<Utc>::from_utc(naive, Utc)\n}\n\n\n#[test]\nfn test_timestamp() {\n let timestamp = 1627127393230;\n let ts = convert(timestamp);\n assert_eq!(ts.to_string(), "2021-07-24 11:49:53.230 UTC")\n}\n\nRun Code Online (Sandbox Code Playgroud)\n
from_timestamp 不支持毫秒。您可以将第二个参数中的毫秒作为纳秒。但你必须将其从时间戳中分离出来。
检查子字符串箱或这样做:
use chrono::{DateTime, NaiveDateTime, Utc};
fn main() {
let timestamp = 1627127393i64;
let nanoseconds = 230 * 1000000;
let datetime = DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(timestamp, nanoseconds), Utc);
println!("{}", datetime);
}
Run Code Online (Sandbox Code Playgroud)
使用子字符串箱:
use substring::Substring;
use chrono::{DateTime, NaiveDateTime, Utc};
fn main() {
let timestamp = "1627127393230";
let nanoseconds = substring(timestamp, 11, 3).parse::<i64>().unwrap() * 1000000;
let timestamp = substring(timestamp, 1, 10).parse::<i64>().unwrap();
let datetime = DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(timestamp, nanoseconds), Utc);
println!("{}", datetime);
}
Run Code Online (Sandbox Code Playgroud)