Golang : Change a file last modified date and time
There are times when we need to perform some operation on a file, but then manually change the last modified and access time of the file.
In this tutorial, we will learn how to change a file last modified time with http://golang.org/pkg/os/#Chtimes function. The Chtimes will require the target filename, atime and mtime.
- atime: time of last access (ls -lu),
- mtime: time of last modification (ls -l)
Below the the code example :
changetime.go
package main
import (
"fmt"
"os"
"time"
)
func main() {
filename := "binary.file"
// get last modified time
file, err := os.Stat(filename)
if err != nil {
fmt.Println(err)
}
modifiedtime := file.ModTime()
fmt.Println("Last modified time : ", modifiedtime)
// get current timestamp
currenttime := time.Now().Local()
fmt.Println("Current time : ", currenttime.Format("2006-01-02 15:04:05 +0800"))
// change both atime and mtime to currenttime
err = os.Chtimes(filename, currenttime, currenttime)
if err != nil {
fmt.Println(err)
}
fmt.Println("Changed the file time information")
}
Result :
localhost:~ admin$ go run changetime.go
Last modified time : 2014-02-12 22:00:18 +0800 MYT <------ original last modified time
Current time : 2014-06-30 14:50:00 +0800
Changed the file time information
localhost:~ admin$ ls -la binary.file
-rwxr-xr-x 1 admin staff 2206048 Jun 30 14:50 binary.file <------- changed to Jun 30
See also : Golang : Get file last modified date and time
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+8.7k Golang : What is the default port number for connecting to MySQL/MariaDB database ?
+16.2k Golang : Read integer from file into array
+40.7k Golang : How to check if a string contains another sub-string?
+12.8k Golang : How to calculate the distance between two coordinates using Haversine formula
+18.9k Golang : Get host name or domain name from IP address
+10.2k Golang : Generate random integer or float number
+8.6k Golang : Gaussian blur on image and camera video feed examples
+14.2k Golang : Send email with attachment(RFC2822) using Gmail API example
+8.8k Golang : Get curl -I or head data from URL example
+17.5k Golang : Login and logout a user after password verification and redirect example
+5.9k Golang : Create new color from command line parameters
+18.3k Golang : Set, Get and List environment variables