home ~ projects ~ socials

Get The Modification Time Of A File In Epoch Seconds In Rust

I use epoch seconds for tracking when files change in my blog engine. There's a built-in std::fs::Metadata struct` that provides access to the time via a .modified() call. That returns a SystemTime2 which takes a little extra work to turn into an integer. This is what that looks like:

```cargo
[dependencies]
anyhow = "1.0.93"
```

use std::fs;
use std::time::UNIX_EPOCH;
use std::path::PathBuf;

fn main() {
    let mod_time = file_epoch_mod_time(&PathBuf::from("./test.txt"));
    match mod_time {
        Ok(t) => { dbg!(t); () },
        Err(e) => { dbg!(e); () }
    };
}

pub fn file_epoch_mod_time(path: &PathBuf) -> anyhow::Result<u64> {
    let base_mod_time = fs::metadata(path)?
        .modified()?
        .duration_since(UNIX_EPOCH)?
        .as_secs();
    Ok(base_mod_time)
}
Output:
[/Users/alan/.cargo/target/55/19854259915251/_active_nvim_run:13:20] t = 1733162420

It's a few hoops but it gets you there.

-- end of line --

References

After kicking around on the docs for an hour this is where I finally found the full answer for how to pull this off