Go os.Chtimes
Restore and verify a file modification time.
A simple example
os.Chtimes
- Start with A practice file and a chosen time
- Do this Set the modification time and read it back
- Result The chosen time, at filesystem precision
Syntax
os.Chtimes(issue, stamp, stamp)
Run these examples in Go
Save one example at a time as main.go. Use Go 1.21 or later.
go run main.goRestore a newsletter publication date
A club restores a newsletter from its backup. The archive uses the publication timestamp to sort issues, so the migration sets a known whole-second time and reads it back before indexing.
package main
import (
"os"
"fmt"
"time"
"path/filepath"
)
func check(err error) {
if err != nil { panic(err) }
}
func main() {
dir, err := os.MkdirTemp("", "lesson-")
check(err)
defer os.RemoveAll(dir)
p := func(name string) string { return filepath.Join(dir, name) }
issue := p("issue")
check(os.WriteFile(issue, nil, 0600))
stamp := time.Unix(1704067200, 0)
check(os.Chtimes(issue, stamp, stamp))
info, err := os.Stat(issue)
check(err)
fmt.Println(info.ModTime().Unix())
}
1704067200
The restored instant is midnight UTC on 1 January 2024, expressed in Unix seconds.
Preserve a concert archive date
The school archives its concert program under the original performance date. After writing the export, set its modification time to noon UTC on the recorded day. Which date does the metadata report back?
Restore a newsletter date
The editor restores the date on a copied issue. After writing the export, set its modification time to noon UTC on the recorded day. Which date does the metadata report back?
What to watch for
Filesystems store different time resolutions. Compare at a supported precision.