Search code examples
rustrust-chrono

How to convert DateTime<UTC> to DateTime<FixedOffset> or vice versa?


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 DateTime::parse_from_str which results in a DateTime<FixedOffset>
  2. The current time, received by UTC::now which results in a DateTime<UTC>.

Is there a way to convert DateTime<UTC> to DateTime<FixedOffset>?


Solution

  • 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<Utc> = 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