Author | Jakob Wakeling <[email protected]> |
Date | 2024-05-23 00:42:30 |
Commit | d88ffe6239539c1dd6f52d02994316b10693dd72 |
Add UNIX time to ISO 8601 and vice versa converter
Diffstat
A | .gitignore | | | 1 | + |
A | Makefile | | | 12 | ++++++++++++ |
A | src/unixtime/go.mod | | | 3 | +++ |
A | src/unixtime/main.go | | | 44 | ++++++++++++++++++++++++++++++++++++++++++++ |
4 files changed, 60 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ae3c172 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/bin/ diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..18b0296 --- /dev/null +++ b/Makefile @@ -0,0 +1,12 @@ +.PHONY: all build test help +all: help + +build: ## Build the project + @go build -C ./src/unixtime -o ../../bin/unixtime . + +test: ## Run unit tests + @go tets ./... + +help: ## Display help information + @grep -E '^[a-zA-Z_-]+:.*?##.*$$' $(MAKEFILE_LIST) | \ + awk 'BEGIN {FS = ":.*?## *"}; {printf "\033[36m%-6s\033[0m %s\n", $$1, $$2}' diff --git a/src/unixtime/go.mod b/src/unixtime/go.mod new file mode 100644 index 0000000..a80322f --- /dev/null +++ b/src/unixtime/go.mod @@ -0,0 +1,3 @@ +module unixtime + +go 1.22 diff --git a/src/unixtime/main.go b/src/unixtime/main.go new file mode 100644 index 0000000..b812d61 --- /dev/null +++ b/src/unixtime/main.go @@ -0,0 +1,44 @@ +package main + +import ( + "fmt" + "log" + "os" + "strconv" + "time" +) + +func main() { + if len(os.Args) < 2 { + fmt.Println("Usage: unixtime timestamp...") + os.Exit(-1) + } + + for _, a := range os.Args[1:] { + fmt.Println(a, "->", unixtime(a)) + } +} + +func unixtime(s string) string { + if isUnixTime(s) { + ns, _ := strconv.ParseInt(s, 10, 64) + t := time.Unix(0, ns).UTC() + return t.Format("2006-01-02T15:04:05.999999Z") + } else { + t, err := time.Parse("2006-01-02T15:04:05.999999Z", s) + if err != nil { + log.Fatalln(err.Error()) + } + + return strconv.FormatInt(t.UnixNano(), 10) + } +} + +func isUnixTime(s string) bool { + for _, r := range s { + if r < '0' || r > '9' { + return false + } + } + return true +}