Search code examples
rustrust-chrono

chrono convert DateTime<Utc> to NaiveDate


After a while of fiddling, I decided to ask the question here, because - others shallst not waste as much fiddling time as I have.

So, how to convert a DateTime<Utc> into a NaiveDate with Rusts chrono crate?

Here the "fill in the blanks" kind of test code:

#[test]
  fn test_utc_now_to_naive_date() {
    let utc_now = Utc::now();
    let now: NaiveDate = ???? // how?
  }

I attribute the fact, that in most languages, time and date function libraries are over- designed monsters to the PTSD people suffered from the Y2K bug...

We have traits like Datelike and should that not help converting one date-like thing into another? Well - I could not find the solution...


Solution

  • The methods DateTime.naive_utc and NaiveDateTime.date are well documented:

    let now: NaiveDate = utc_now.naive_utc().date();
    

    Or the even simpler version from Jonas' comment, using DateTime.date_naive:

    let now = utc_now.date_naive();