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

I have a structure that contains a timestamp. For this, I use the chronological library . There are two ways to get the timestamp:

  • Parsed from string through DateTime::parse_from_str

    , resulting inDateTime<FixedOffset>

  • The current time received UTC::now

    , which results in DateTime<UTC>

    .

Is there a way to convert DateTime<UTC>

to DateTime<FixedOffset>

?

+3


source to share


1 answer


I believe what you are looking for is 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 added a redundant type annotation in then_utc

to show that 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

      

+6


source







All Articles