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.
Info Now returns the current time—it will change each day the program is run, and is always current.
Here We pass the full file name with its path to the 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
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 23, 2023 (edit).