tools

Miscellaneous software tools
git clone http://git.omkov.net/tools
Log | Tree | Refs | Download

tools/src/unixtime/main.go (45 lines, 701 B) -rw-r--r-- blame download

01234567891011121314151617181920212223242526272829303132333435363738394041424344
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
}