How to convert DateTime to DateTime or vice versa?

前端 未结 1 1145
我在风中等你
我在风中等你 2021-01-18 21:50

I have a struct that contains a timestamp. For that I am using the chrono library. There are two ways to get the timestamp:

  1. Parsed from a string via Date
1条回答
  •  -上瘾入骨i
    2021-01-18 22:38

    I believe that you are looking for DateTime::with_timezone:

    use chrono::{DateTime, Local, TimeZone, Utc}; // 0.4.9
    
    fn main() {
        let now = Utc::now();
        let then = Local
            .datetime_from_str("Thu Jul  2 23:26:06 EDT 2015", "%a %h %d %H:%M:%S EDT %Y")
            .unwrap();
    
        println!("{}", now);
        println!("{}", then);
    
        let then_utc: DateTime = then.with_timezone(&Utc);
    
        println!("{}", then_utc);
    }
    

    I've added a redundant type annotation on then_utc to show it is in UTC. This code prints

    2019-10-02 15:18:52.247884539 UTC
    2015-07-02 23:26:06 +00:00
    2015-07-02 23:26:06 UTC
    

    0 讨论(0)
提交回复
热议问题