Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 432
angelius Avatar asked Nov 28 '11 09:11

angelius


3 Answers

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
like image 90
tux21b Avatar answered Nov 08 '22 20:11

tux21b


Alternatively, after the Stat you can also do

statinfo.ModTime()

Also you can use Format() on it, should you need it eg for a webserver

see https://gist.github.com/alexisrobert/982674

like image 21
koda Avatar answered Nov 08 '22 19:11

koda


By casting os.FileInfo to *syscall.Stat_t:

package main

import ( "fmt"; "log"; "os"; "syscall"; "time" )

func main() {
    for _, arg := range os.Args[1:] {
        fileinfo, err := os.Stat(arg)
        if err != nil {
            log.Fatal(err)
        }
        atime := fileinfo.Sys().(*syscall.Stat_t).Atim
        fmt.Println(time.Unix(atime.Sec, atime.Nsec))
    }
}
like image 7
atomsymbol Avatar answered Nov 08 '22 20:11

atomsymbol