5

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

1
  • 2
    not unless the underlying filesystem stores atime/ctime/mtime with that kind of precision. can't get what isn't available.
    – Marc B
    Nov 14, 2012 at 16:18

1 Answer 1

8

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.