【问题标题】:Converting from NaiveDateTime to DateTime<Local> [duplicate]从 NaiveDateTime 转换为 DateTime<Local> [重复]
【发布时间】:2020-05-06 22:28:29
【问题描述】:

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

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

不幸的是,我似乎不知道该怎么做。使用Local::From 不起作用。使用DateTime&lt;Local&gt;::from() 也不起作用。两个结构都没有从NaiveDateTime 转换的方法,而NaiveDateTime 没有转换为Local 的方法。

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

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

【问题讨论】:

    标签: rust


    【解决方案1】:

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

    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)

    【讨论】:

      猜你喜欢
      • 2018-06-22
      • 2014-08-12
      • 1970-01-01
      • 2015-04-29
      • 2023-03-21
      • 2019-06-24
      • 2020-05-22
      • 2014-01-15
      • 2010-11-04
      相关资源
      最近更新 更多