How to get last-accessed date and time of file in Go?

angelius picture angelius · Nov 28, 2011 · Viewed 16.1k times · Source

Does anyone know how to check for a file access date and time? The function returns the modified date and time and I need something that compares the accessed date time to the current date and time.

Answer

tux21b picture tux21b · Nov 28, 2011

You can use os.Stat to get a FileInfo struct which also contains the last access time (as well as the last modified and the last status change time).

info, err := os.Stat("example.txt")
if err != nil {
     // TODO: handle errors (e.g. file not found)
}
// info.Atime_ns now contains the last access time
// (in nanoseconds since the unix epoch)

After that, you can use time.Nanoseconds to get the current time (also in nanoseconds since the unix epoch, January 1, 1970 00:00:00 UTC). To get the duration in nanoseconds, just subtract those two values:

duration := time.Nanoseconds() - info.Atime_ns