gpt4 book ai didi

rust - 从 NaiveDateTime 转换为 DateTime

转载 作者:行者123 更新时间:2023-12-03 11:41:24 30 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





How do I go from a NaiveDate to a specific TimeZone with Chrono?

(3 个回答)


2年前关闭。




rust 的 chrono使用它非常令人沮丧,因为它使得从时区转换非常困难。

例如:我的用户输入一个字符串。我使用 NaiveDateTime::parse_from_str 将其解析为一个简单的日期时间.现在我想把它转换成 DateTime<Local> .

不幸的是,我似乎不知道该怎么做。使用 Local::From不起作用。使用 DateTime<Local>::from()也不行。两个结构都没有从 NaiveDateTime 转换的方法。 , 和 NaiveDateTime没有方法可以转换为 Local .

然而,我们可以这样做:someLocalDateTime.date().and_time(some_naive_time) .那么为什么我们不能做 Local::new(some_naive_date_time) ?

另外,为什么我们不能跳过解析中的字段?我不需要秒,也不需要年份。为了假设当前年份和 0 秒,我必须手动编写解析代码并从 ymd hms 构造日期时间。

最佳答案

此功能由 the chrono::offset::TimeZone trait 提供.具体来说,方法 TimeZone::from_local_datetime 几乎正是您正在寻找的。

use chrono::{offset::TimeZone, DateTime, Local, NaiveDateTime};

fn main() {
let naive = NaiveDateTime::parse_from_str("2020-11-12T5:52:46", "%Y-%m-%dT%H:%M:%S").unwrap();
let date_time: DateTime<Local> = Local.from_local_datetime(&naive).unwrap();
println!("{:?}", date_time);
}

(playground)

至于关于用假设进行解析的另一个问题,我不确定这些工具是否存在。如果 ParseResult 会很酷允许您在展开(或您有什么)结果之前手动设置特定值。

一个让你仍然可以使用 chrono 的想法的解析器是手动将额外的字段添加到解析字符串中。

例如:

use chrono::{offset::TimeZone, DateTime, Datelike, Local, NaiveDateTime};

fn main() {
let time_string = "11-12T5:52"; // no year or seconds
let current_year = Local::now().year();
let modified_time_string = format!("{}&{}:{}", time_string, current_year, 0);

let naive = NaiveDateTime::parse_from_str(&modified_time_string, "%m-%dT%H:%M&%Y:%S").unwrap();
let date_time: DateTime<Local> = Local.from_local_datetime(&naive).unwrap();
println!("{:?}", date_time); // prints (as of 2020) 2020-11-12T05:52:00+00:00
}

(playground)

关于rust - 从 NaiveDateTime 转换为 DateTime<Local>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61646536/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com