如何在Go中获取文件的最后访问日期和时间?

huangapple go评论86阅读模式
英文:

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.

答案1

得分: 19

你可以使用os.Stat来获取一个包含最后访问时间的FileInfo结构体(同时也包含最后修改和最后状态更改时间)。

info, err := os.Stat("example.txt")
if err != nil {
     // TODO: 处理错误(例如文件未找到)
}
// info.Atime_ns 现在包含最后访问时间
// (以纳秒为单位,自Unix纪元以来)

之后,你可以使用time.Nanoseconds来获取当前时间(也是自Unix纪元以来的纳秒数,即1970年1月1日00:00:00 UTC)。要获取纳秒级的持续时间,只需将这两个值相减:

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

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

答案2

得分: 9

通过将os.FileInfo转换为*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))
    }
}
英文:

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))
    }
}

答案3

得分: 6

另外,在 Stat 后,你也可以执行以下操作:

statinfo.ModTime()

如果需要,你还可以对其使用 Format(),例如用于 web 服务器

参见 https://gist.github.com/alexisrobert/982674

英文:

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

答案4

得分: 0

For windows

syscall.Win32FileAttributeData

info, _ := os.Stat("test.txt")
fileTime := info.Sys().(*syscall.Win32FileAttributeData).LastAccessTime
aTime := time.Unix(0, fileTime.Nanoseconds())

Example

package main

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

func main() {
	info, _ := os.Stat("./test.txt")
	fileTime := info.Sys().(*syscall.Win32FileAttributeData).LastAccessTime
	// _ = info.Sys().(*syscall.Win32FileAttributeData).CreationTime
	// _ = info.Sys().(*syscall.Win32FileAttributeData).LastWriteTime
	fileAccessTime := time.Unix(0, fileTime.Nanoseconds())

	// Compare
	// t2, _ := time.Parse("2006/01/02 15:04:05 -07:00:00", "2023/02/08 13:18:00 +08:00:00")
	now := time.Now()
	log.Println(fileAccessTime)
	log.Println(now.Add(-20 * time.Minute))
	if fileAccessTime.After(now.Add(-20 * time.Minute)) {
		fmt.Println("You accessed this file 20 minutes ago.")
	}
}

Linux

see this answer

英文:

For windows

syscall.Win32FileAttributeData

info, _ := os.Stat("test.txt")
fileTime := info.Sys().(*syscall.Win32FileAttributeData).LastAccessTime
aTime := time.Unix(0, fileTime.Nanoseconds())

Example

package main

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

func main() {
	info, _ := os.Stat("./test.txt")
	fileTime := info.Sys().(*syscall.Win32FileAttributeData).LastAccessTime
	// _ = info.Sys().(*syscall.Win32FileAttributeData).CreationTime
	// _ = info.Sys().(*syscall.Win32FileAttributeData).LastWriteTime
	fileAccessTime := time.Unix(0, fileTime.Nanoseconds())

	// Compare
	// t2, _ := time.Parse("2006/01/02 15:04:05 -07:00:00", "2023/02/08 13:18:00 +08:00:00")
	now := time.Now()
	log.Println(fileAccessTime)
	log.Println(now.Add(-20 * time.Minute))
	if fileAccessTime.After(now.Add(-20 * time.Minute)) {
		fmt.Println("You accessed this file 20 minutes ago.")
	}
}

Linux

see this answer

huangapple
  • 本文由 发表于 2011年11月28日 17:57:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/8294134.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定