从 NaiveDateTime 转换为 DateTime<Local>

Tho*_*eia 0 rust

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

例如:我的用户输入一个字符串。我使用NaiveDateTime::parse_from_str. 现在我想将其转换为DateTime<Local>.

不幸的是,我似乎无法找到如何这样做。使用Local::From不起作用。使用DateTime<Local>::from()也不行。两个结构都没有从 a 转换的方法NaiveDateTimeNaiveDateTime也没有转换为 的方法Local

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

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

SCa*_*lla 7

此功能是通过提供chrono::offset::TimeZone特质。具体来说,该方法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);
}
Run Code Online (Sandbox Code Playgroud)

(操场)


至于关于假设解析的另一个问题,我不确定这些工具是否存在。如果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
}
Run Code Online (Sandbox Code Playgroud)

(操场)