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.
Consider this Go example program. We introduce a GetFilenameDate
method, and this returns a file name with the current date.
ioutil.WriteFile
func
. Check the target folder, and the file will exist.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
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.
GetFilenameDate
func
, we could place the program's output in a file with a useful name.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.