0

I am trying to convert a string to a date using the Chrono library. I always get a BadFormat or NotEnough error:

extern crate chrono;

use chrono::prelude::*;

fn main() {
    let dt1 = DateTime::parse_from_str(
        "2017-08-30 18:34:06.638997932 UTC", 
        "%Y-%m-%d %H:%M:%S.%9f"
    );
    println!("{:?}", dt1);
}

I'm not sure what I am doing wrong.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
user1916077
  • 431
  • 1
  • 7
  • 18

1 Answers1

2
  1. As mentioned in the comments, your format string doesn't allow for the " UTC" part of your string. That's why you get the BadFormat error.

  2. If you add " UTC" to your format string, you still get a BadFormat error because you've typed .%9f when it should be %.9f.

  3. Once you fix that, you get a NotEnough error because we aren't actually parsing a timezone.

I'd use NaiveDateTime to always parse in UTC and then add the " UTC" onto the format string to ignore it, correcting the typo:

use chrono::prelude::*; // 0.4.9

fn main() {
    let dt1 = NaiveDateTime::parse_from_str(
        "2017-08-30 18:34:06.638997932 UTC",
        "%Y-%m-%d %H:%M:%S%.9f UTC",
    );

    println!("{:?}", dt1); // Ok(2017-08-30T18:34:06.638997932)
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • How can I parse a `String` instead of a `&'static str`? All examples from Chrono are always using `&'static str`. But that's not how you do it in a real program. In production you use `String` for everything. – TheFox Dec 17 '19 at 17:03
  • 1
    @TheFox [What is the idiomatic way to convert a String to &str?](https://stackoverflow.com/q/29026066/155423); [Idiomatic transformations for String, &str, Vec and &\[u8\]](https://stackoverflow.com/q/41034635/155423); [Why is it discouraged to accept a reference to a String (&String), Vec (&Vec), or Box (&Box) as a function argument?](https://stackoverflow.com/q/40006219/155423). TL;DR: if you have a `s: String`, you can pass `&s` and it will become a `&str` – Shepmaster Dec 17 '19 at 17:17