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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Feb 23, 2023 (edit).