How compare dates between folder creation and time now

Hello, How i compare dates between folder modification(creation) and time now.
for example:
if date_now() == date_metadata() {
println!("equal")
}

fn date_now() -> String {
    let utc_time: DateTime<Utc> = Utc::now();
    let local_time: DateTime<Local> = utc_time.with_timezone(&Local);
    let formatted_date = local_time.format("%Y-%m-%d %H:%M:%S").to_string();
    formatted_date
// return 2023-07-29 22:43:09
}

fn date_metadata() {
   let metadata = fs::metadata("/home/pichi/book/the glory/");
    let last_modified = metadata.expect("REASON").modified().expect("REASON").elapsed().expect("REASON").as_secs();
    println!("last_modified: {}", last_modified);
last_modified
// return last_modified: 1052
}

There are a lot of details to "compare" because SystemTime is non-monotonic. Have you read the docs of SystemTime?

1 Like

Here's a code snippet I use to update a file only if it's older than 20 minutes:

// Added for clarification:
let path = PathBuf::from("/home/pichi/book/the glory/file.txt");

// Snippet in use:
if path.is_file() {
  let modified = match path.metadata().unwrap().modified() {
    Ok(time) => time,
    Err(_) => SystemTime::now(),
  };

  match SystemTime::now().duration_since(modified) {
    Ok(file_age) => {
      if file_age.as_secs() < 1200 /* 20 minutes in seconds */ {
        // File too young for update.
        return Ok(());
      }
    },
    Err(_) => {},
  }
  // ... update the file ...
}

Looking at your example: current time and file modification time will never be exactly equal, even if you call SystemTime::now() right after writing the file. Processing a line of code takes time, processing of the file in the operating system as well, so there's always a distinction. One can only look at the age and whether that's too high.

1 Like

Thanks thanks a lot. :saluting_face:
Wonderful people here.

1 Like