sheyrl
sheyrl

Reputation: 25

How to turn the file-created-time into an integer?

With fs::Metadata::created, I can get the created time of the file.

To compare between files in seconds, not milliseconds or whatever, the simple way is to turn the created time into an integer measured in seconds...

But how?

Upvotes: 1

Views: 496

Answers (1)

Outfrost
Outfrost

Reputation: 202

Welcome to Stack Overflow!

You can directly compare instances of std::time::SystemTime that you get from std::fs::Metadata::created(), but I assume your use case specifically requires second-precision comparisons. In that case:

SystemTime itself does not offer unit conversion methods, but it does offer duration_since() and the constant UNIX_EPOCH. From the documentation:

pub const UNIX_EPOCH: SystemTime

An anchor in time which can be used to create new SystemTime instances or learn about where in time a SystemTime lies.

This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with respect to the system clock.

Once you provide this kind of point of reference to duration_since(), and obtain a Duration, you can use Duration's unit conversion methods to get the integers that you need. Example:

let a = someFileMetadata.created().expect("Creation time unsupported");
let b = someOtherFileMetadata.created().expect("Creation time unsupported");

let a_secs = a.duration_since(SystemTime::UNIX_EPOCH)
              .expect("File A thinks it was created before Epoch")
              .as_secs();
let b_secs = b.duration_since(SystemTime::UNIX_EPOCH)
              .expect("File B thinks it was created before Epoch")
              .as_secs();

if a_secs > b_secs {
    println!("File A was created later than file B!");
}

Upvotes: 1

Related Questions