Golang Filename With Date Example (time.Now)Create a file with the current date in the file name. Use the file to record data each day it is run.
Filename, date. Consider a Go program that is run each day, and outputs a report. We want to place its output in a file name that contains the current day.
With time.Now, we can get the current time. And we can convert this to a string with the Format func. We can even provide a pattern to specify delimiter chars.
An example. Consider this Go example program. We introduce a GetFilenameDate method, and this returns a file name with the current date.
Time.Now This returns the current time—it will change each day the program is run, and is always current.
WriteFile We pass the full file name with its path to the ioutil.WriteFile func. Check the target folder, and the file will exist.
Golang program that uses time in filename
package main import ( "fmt" "io/ioutil" "time" ) func GetFilenameDate() string { // Use layout string for time format. const layout = "01-02-2006" // Place now in the string. t := time.Now() return "file-" + t.Format(layout) + ".txt" } func main() { name := GetFilenameDate() fmt.Println("Name:", name) ioutil.WriteFile("C:\\programs\\" + name, []byte("Contents"), 0) }
Name: file-06-18-2020.txt
A utility method. Consider a Go program that downloads server logs and collects usage stats. It can be run once per day, and output its result in a file.
And With the GetFilenameDate func, we could place the program's output in a file with a useful name.
A summary. The important part here is to use Format on the time instance to get a string containing the date. Then we can create the full path from that file name.
© 2007-2021 sam allen. see site info on the changelog