Search code examples
rustfilesystemsrust-chrono

How to create a file/directory with a name from DateTime::format()?


I would like to make directory with a name in "%Y%m%y_%H%M%S" format, but trying to use the result of .format() directly causes an error:

use std::fs;
use chrono;

fn main() {
    let now = chrono::offset::Local::now();
    let custom_datetime_format = now.format("%Y%m%y_%H%M%S");
    println!("{:}", custom_datetime_format);

    let new_dir = fs::create_dir(custom_datetime_format).unwrap(); 
    println!("New directory created");
    println!("{:#?}", new_dir);
}
error[E0277]: the trait bound `DelayedFormat<StrftimeItems<'_>>: AsRef<Path>` is not satisfied
    --> src/main.rs:9:34
     |
9    |     let new_dir = fs::create_dir(custom_datetime_format).unwrap(); 
     |                   -------------- ^^^^^^^^^^^^^^^^^^^^^^ the trait `AsRef<Path>` is not implemented for `DelayedFormat<StrftimeItems<'_>>`
     |                   |
     |                   required by a bound introduced by this call
     |
note: required by a bound in `create_dir`
    --> /Users/macbook/.rustup/toolchains/stable-x86_64-apple-darwin/lib/rustlib/src/rust/library/std/src/fs.rs:1977:22
     |
1977 | pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
     |                      ^^^^^^^^^^^ required by this bound in `create_dir`

From my current understanding problem is that create_dir() expects the parameter to implement AsRef<Path>. Any idea how to convert DelayedFormat<StrftimeItems<'_>> to a AsRef<Path>? Or this is all wrong?


Solution

  • Because your datetime doesn't implement AsRef<Path> you have to convert the datetime to a String first. One way is the one you found yourself:

    fs::create_dir(format!("{custom_datetime_format}")).unwrap();
    

    or you use it's ToString implementation which is implemented for every type that implements Display:

    fs::create_dir(custom_datetime_format.to_string()).unwrap();