Video Coming Soon...
35: date
The date command is deceptively simple, and there are two layers to its difficulty. One way to approach this is to just "Go with it" and use Go's default formatting and date output. You could make that version of date very easily.
The other way to do this is to attempt to implement all of the formatting and output styles that the original supports. GNU date uses an older style of date formatting that requires far more work since it's not directly supported by Go.
I'd say, if you want to learn how to use Go date/time facilities, then just do the first one. If you want to learn how to write code that parses complex inputs then try to replicate GNU's date.
The Challenge
The official documentation for GNU date is at:
I would first implement as much as you can with only Go's outputs and formats. Then if you want to go further try implementing GNU's date format by hand.
Requirements
My simple little implementation didn't use much, just time is the only new package. If you go for the full GNU date then you'll most likely use more, but probably not much more.
See the list of requirements
- fmt -- https://pkg.go.dev/fmt
- time -- https://pkg.go.dev/time
- flag -- https://pkg.go.dev/flag
Spoilers
Mine is so simple that it all fits in the main() function, but it also doesn't do much more than output the current date using default Go outputs.
See my first version code
View Source file go-coreutils/date/main.go Onlypackage main
import (
"fmt"
"time"
"flag"
)
func main() {
var result string
var universal bool
it_is := time.Now()
flag.BoolVar(&universal, "u", false, "UTC time.")
flag.Parse()
if universal {
it_is = it_is.UTC()
}
if flag.NArg() == 1 {
result = it_is.Format(flag.Args()[0])
} else {
result = it_is.String()
}
fmt.Println(result)
}
Testing It
If you want to push your learning further then you can try to implement an automated test for this. I actually need to learn how to test utilities like this with Go, so for now just consider this an extra challenge for later until I learn how to teach it.
Register for Learn Go the Hard Way
Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.