如何将文件创建时间转换为整数?

问题描述 投票:1回答:1

通过fs :: Metadata :: created,我可以获取文件的创建时间。

要以秒而不是毫秒为单位在文件之间进行比较,简单的方法是将创建的时间转换为以秒为单位的整数...

但是如何?

rust
1个回答
0
投票

欢迎使用堆栈溢出!

您可以直接比较从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!");
}
© www.soinside.com 2019 - 2024. All rights reserved.