how to get last modification time of a file with epoch time format, precision millisecond on linux system
I tried stat, but it can only show epoch time in seconds are there any simple ways to get epoch time in millisecond
If you're on a filesystem that supports sub-second precision (for example ext4 supports it, ext3 does not), then you can get nanosecond precision through the st_atim.tv_nsec
, st_ctim.tv_nsec
and st_mtim.tv_nsec
fields of struct stat
. The values represent the amount of nanoseconds in addition to the amount of seconds in st_atime
and friends. For example, you can get millisecond timestamps with:
struct stat info;
stat("/etc", &info);
uint64_t access_ms = info.st_atime * 1000 + info.st_atim.tv_nsec / 1000000;
uint64_t status_ms = info.st_ctime * 1000 + info.st_ctim.tv_nsec / 1000000;
uint64_t modification_ms = info.st_mtime * 1000 + info.st_mtim.tv_nsec / 1000000;
A second has 1000ms, so you multiply by that. A millisecond has 1000000ns, so you divide by that.
If the filesystem does not support sub-second precision, then the tv_nsec
fields will always be 0. This ensures that the same code will also work on filesystems that don't support sub-second precision.
Note that the amount of milliseconds since epoch can't be stored in a 32-bit value. You need at least 64 bits. uint64_t
is provided by <stdint.h>
. Alternatively, you can use unsigned long long
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With