Home > Backend Development > Golang > How Can I Get a File\'s Creation Date in Windows Using Go?

How Can I Get a File\'s Creation Date in Windows Using Go?

Barbara Streisand
Release: 2024-11-20 18:54:14
Original
216 people have browsed it

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)
}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template