通过fs :: Metadata :: created,我可以获取文件的创建时间。
要以秒而不是毫秒为单位在文件之间进行比较,简单的方法是将创建的时间转换为以秒为单位的整数...
但是如何?
欢迎使用堆栈溢出!
您可以直接比较从std::time::SystemTime
中获得的std::fs::Metadata::created()
的实例,但是我认为您的用例特别需要二精度比较。在这种情况下:
SystemTime
本身不提供单位转换方法,但确实提供了duration_since()
和常数UNIX_EPOCH
。从the documentation:
pub const UNIX_EPOCH: SystemTime
时间锚,可用于创建新的
SystemTime
实例或了解SystemTime
的时间。相对于系统时钟,在所有系统上此常量定义为“ 1970-01-01 00:00:00 UTC”。
一旦提供了对duration_since()
的这种参考,并获得了Duration
,就可以使用Duration
的单位转换方法来获得所需的整数。示例:
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!");
}