Parsing a datetime string to local time in rust chrono

Viewed 1236

Having trouble with a simple problem. I have a string that does not include timezone information that I need to parse into a DateTime struct. I can get it as UTC, but not local:

let from = NaiveDateTime::parse_from_str(&start_date, "%Y-%m-%dT%H:%M:%S")?;
let from_utc = DateTime::<Utc>::from_utc(from, Utc);
1 Answers

You need Local.from_local_datetime() to convert a NaiveDateTime into a DateTime<Local>:

let from: NaiveDateTime = start_date.parse().unwrap();
let date_time = Local.from_local_datetime(&from).unwrap();

Admittedly, this isn't really easy to find in the documentation.

The first line you have works fine as well. For this particular format (RFC3339), it's easier to use str::parse(), though.

Related