forked from yanghang8612/tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
timecmd.go
69 lines (65 loc) · 2.72 KB
/
timecmd.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package main
import (
"tools/log"
"strconv"
"strings"
"time"
"github.com/urfave/cli/v2"
)
var (
nowCommand = cli.Command{
Name: "now",
Usage: "Convert time between datetime and timestamp",
Action: func(c *cli.Context) error {
// display now
if c.NArg() == 0 {
log.NewLog("in sec", time.Now().Unix())
log.NewLog("in milli", time.Now().UnixMilli())
log.NewLog("in datetime", time.Now())
} else {
arg := c.Args().Get(0)
ts, err := strconv.Atoi(arg)
// input str is timestamp
if err == nil {
var dt time.Time
dt = time.Unix(int64(ts), 0)
// only display date in 21st Century
if dt.Year() >= 2000 && dt.Year() <= 2100 {
log.NewLog("in sec", dt.Format("2006-01-02 15:04:05"))
}
dt = time.Unix(int64(ts/1000), 0)
// only display date in 21st Century
if dt.Year() >= 2000 && dt.Year() <= 2100 {
log.NewLog("in milli", dt.Format("2006-01-02 15:04:05"))
}
} else {
// input str is date or time
loc, _ := time.LoadLocation("Asia/Shanghai")
formatsWithDateButNoYear := []string{"1-2 15:4:5", "1-2 15:4", "1-2 15", "1-2"}
formatsWithoutDate := []string{"15:4:5", "15:4"}
formats := formatsWithDateButNoYear
// append two kinds of year to formats
for _, f := range formatsWithDateButNoYear {
formats = append(formats, "2006-"+f)
formats = append(formats, "06-"+f)
}
formats = append(formats, formatsWithoutDate...)
for _, format := range formats {
if dt, err := time.ParseInLocation(format, arg, loc); err == nil {
if !strings.ContainsAny(format, "-") {
dt = dt.AddDate(time.Now().Year(), int(time.Now().Month())-1, time.Now().Day()-1)
}
if dt.Year() == 0 {
dt = dt.AddDate(time.Now().Year(), 0, 0)
}
log.NewLog("in sec", dt.Unix())
log.NewLog("in milli", dt.UnixMilli())
log.NewLog("in datetime", dt)
}
}
}
}
return nil
},
}
)