Mismatched types expected struct `DateTime<Utc>` found struct `DateTime<FixedOffset>

Hello

This is my code:

let date: chrono::DateTime<chrono::Utc> = chrono::DateTime::parse_from_str(
        &*format!("{y}-{m}-1", y = "2021", m = "12"),
        "%Y-%m-%d",
    );

I am just trying to get a DateTime from a String...
This is the error I get though:

mismatched types expected struct `DateTime<Utc>` found struct `DateTime<FixedOffset>

How would I fix this?

1 Like

I don't know if there's a better way, but this works:

use chrono::{DateTime, NaiveDate, ParseError, Utc};

fn main() -> Result<(), ParseError> {
    let nd = NaiveDate::parse_from_str(
        &*format!("{y}-{m}-1", y = "2021", m = "12"),
        "%Y-%m-%d",
    )?;

    let date: DateTime<Utc> = DateTime::from_utc(nd.and_hms(0, 0, 0), Utc);

    println!("{}", date);
    Ok(())
}

I think a better option would be to not fight the parser API and explicitly specify the time zone instead. DateTime<Utc> implements From<DateTime<FixedOffset>>, and naïve dates are almost never what one needs/wants anyway. Playground:

fn main() -> Result<(), ParseError> {
    let date = DateTime::parse_from_str(
        &*format!("{y}-{m}-01 00:00:00 +0000", y = "2021", m = "12"),
        "%Y-%m-%d %H:%M:%S %z",
    )?;
    let date = DateTime::<Utc>::from(date);
    
    println!("{}", date);
    Ok(())
}
3 Likes
    fn parse_date(date: &str) -> anyhow::Result<chrono::DateTime<chrono::Utc>> {
        //     let d = DateTime::parse_from_str(date, "%Y-%m-%d %H:%M:%S %z")?;
        //     let d = DateTime::<chrono::Utc>::from(d);
        //     Ok(d)
        DateTime::parse_from_str(date, "%Y-%m-%d %H:%M:%S %z")
            .map(|dt| dt.into())
            .map_err(|e| e.into())
    }

A better way to convert DateTime<FixedOffset> into DateTime<Utc> is to leverage From trait and use map function to do value convertion.

You can also use map_err to convert errors: ParseError => anyhow::Error.

I am already using said From impl in the example I provided. I don't see any significant difference between the behavior of my code and the function you wrote.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.