diff --git a/cmd/main.go b/cmd/main.go index 225550c..d62cd9c 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -4,6 +4,7 @@ import ( "fmt" "io" "os" + "strings" "time" "github.com/araddon/dateparse" @@ -35,11 +36,16 @@ func Main(cmd *cobra.Command, args []string) error { //times times := make([]time.Time, 0, len(args)+1) if len(args) == 0 { - times = append(times, time.Now()) + t := time.Now() + t = t.Add(viper.GetDuration("add")) + t = t.Add(-viper.GetDuration("sub")) + times = append(times, t) } for _, arg := range args { - t, err := dateparse.ParseStrict(arg) + t, err := dateparse.ParseStrict(strings.TrimSpace(arg)) exitForErr(err) + t = t.Add(viper.GetDuration("add")) + t = t.Add(-viper.GetDuration("sub")) times = append(times, t) } @@ -81,8 +87,8 @@ func Main(cmd *cobra.Command, args []string) error { // StampMilli = "Jan _2 15:04:05.000" // StampMicro = "Jan _2 15:04:05.000000" // StampNano = "Jan _2 15:04:05.000000000" - dest := fmt.Sprint(time.Now().UnixNano() / 1000000) if len(viper.GetString("format")) > 0 { + dest := "" switch viper.GetString("format") { case "ANSIC": dest = time.ANSIC @@ -119,8 +125,10 @@ func Main(cmd *cobra.Command, args []string) error { exitForErr(err) dest = d } + fmt.Fprintln(stdout, tm.Format(dest)) + continue } - fmt.Fprintln(stdout, tm.Format(dest)) + fmt.Fprintln(stdout, tm.UnixNano()/1000000) } return nil } diff --git a/cmd/root.go b/cmd/root.go index 1123c19..f238073 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -4,6 +4,7 @@ import ( "fmt" "io/ioutil" "os" + "time" "github.com/spf13/cobra" "github.com/spf13/viper" @@ -16,11 +17,15 @@ func RootCmd() *cobra.Command { Use: "ts", Short: "timestamp convert & compare tool", Example: ` - (timestamp) $: ts - (format) $: ts -f "2019/06/25 23:30:10" - (before) $: ts -b "2019/06/25 23:30:10" ; echo $? - (after) $: ts -a "2019/06/25 23:30:10" ; echo $? - (timezone) $: ts -f "2019/06/25 23:30:10" -z "Asia/Shanghai" + (now timestamp) $: ts + (now add) $: ts --add 1d + (now sub) $: ts --sub 1d + (convert) $: ts "2019/06/24 23:30:10" + (pipe) $: echo "2019/06/24 23:30:10" | ts + (format) $: ts -f "2019/06/25 23:30:10" + (before) $: ts -b "2019/06/25 23:30:10" ; echo $? + (after) $: ts -a "2019/06/25 23:30:10" ; echo $? + (timezone) $: ts -f "2019/06/25 23:30:10" -z "Asia/Shanghai" `, Run: func(cmd *cobra.Command, args []string) { //pipe stdin @@ -37,10 +42,13 @@ func RootCmd() *cobra.Command { exitForErr(Main(cmd, args)) }, } + cmd.Flags().StringP("after", "a", "", "after compare") cmd.Flags().StringP("before", "b", "", "before compare") cmd.Flags().StringP("format", "f", "", "time format") cmd.Flags().StringP("timezone", "z", "", "time zone") + cmd.Flags().DurationP("add", "", 0*time.Second, "add duration") + cmd.Flags().DurationP("sub", "", 0*time.Second, "sub duration") return cmd }