Home >Backend Development >Golang >How Can I Get a File\'s Creation Date in Windows Using Go?
Determining File Creation Date in Windows Using Go
Determining the creation date of a file in Windows using Go can be achieved leveraging the os package and by targeting the Windows-specific system data structures.
The os.Stat function provides access to the file's metadata, but it does not include the creation date. Instead, you need to use the FileInfo.Sys() method to retrieve the underlying system-specific data structures, which in the case of Windows is a syscall.Win32FileAttributeData struct.
The Win32FileAttributeData struct contains various attributes, including the CreationTime field. This field represents the file's creation timestamp as a Filetime structure. To convert it into a human-readable time value, use the time.Unix function with a nanosecond precision factor.
Here's an example code snippet:
package main import ( "fmt" "os" "syscall" "time" ) func main() { fi, err := os.Stat("test.txt") if err != nil { panic(err) } // Ensure platform is Windows. if os.Name != "windows" { panic("This example is only valid for Windows.") } d := fi.Sys().(*syscall.Win32FileAttributeData) cTime := time.Unix(0, d.CreationTime.Nanoseconds()) fmt.Println("File creation date:", cTime) }
Remember to protect this Windows-specific code using build constraints, either within a dedicated _windows.go file or by using the //go:build windows syntax.
The above is the detailed content of How Can I Get a File\'s Creation Date in Windows Using Go?. For more information, please follow other related articles on the PHP Chinese website!