-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdateconv.go
More file actions
118 lines (101 loc) · 2.44 KB
/
Copy pathdateconv.go
File metadata and controls
118 lines (101 loc) · 2.44 KB
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"os/user"
"path/filepath"
"strings"
"time"
"github.com/kierdavis/dateparser"
)
func main() {
var (
dayFirst = flag.Bool("df", false, "Disambiguate day-month as day first (like in the US)")
yearFirst = flag.Bool("yf", false, "Disambiguate 2-digit yeas (yy-mm-dd/dd-mm-yy) as years first")
fuzzy = flag.Bool("fuzzy", false, "Allow more resilient fuzzy matching")
format = flag.String("format", time.RFC850, "Output format, Golang output format rules")
config = flag.String("conf", "", "Extra config/timezone json mappings")
// In order of precedence
toUTC = flag.Bool("utc", false, "Converts date to UTC format")
toTs = flag.Bool("ts", false, "Converts date to Unix timestamp")
toTsNano = flag.Bool("tsNano", false, "Converts date to Unix timestamp with nanoseconds")
toTz = flag.String("tz", "local", "To specific Timezone. Defaults to local.")
)
flag.Parse()
if flag.NArg() > 1 {
flag.Usage()
os.Exit(1)
}
var dt time.Time
if flag.NArg() == 1 && flag.Args()[0] != "" {
var (
toParse = flag.Args()[0]
err error
)
// Attempt to load config, or fail silently
tzInfos := loadConf(*config)
parser := &dateparser.Parser{
DayFirst: *dayFirst,
YearFirst: *yearFirst,
Fuzzy: *fuzzy,
TZInfos: tzInfos,
}
dt, err = parser.Parse(toParse)
if err != nil {
log.Fatal(err)
}
} else {
// Default
dt = time.Now()
}
// Now just print the output in the date on the desired format
switch {
case *toUTC:
fmt.Println(dt.UTC().Format(*format))
case *toTs:
fmt.Println(dt.Unix())
case *toTsNano:
fmt.Println(dt.UnixNano())
default: // To timezone
if strings.ToLower(*toTz) == "local" {
fmt.Println(dt.Local().Format(*format))
} else {
loc, err := time.LoadLocation(*toTz)
if err != nil {
log.Fatal(err)
}
fmt.Println(dt.In(loc).Format(*format))
}
}
}
func loadConf(path string) map[string]int {
if path == "" {
// Attempt default at ~/.dateconv
homedir, err := getHomeDir()
if err != nil {
return nil
}
path = filepath.Join(homedir, ".dateconv")
}
conf, err := ioutil.ReadFile(path)
if err != nil {
return nil
}
var tzInfos map[string]int
err = json.Unmarshal(conf, &tzInfos)
if err != nil {
return nil
}
return tzInfos
}
func getHomeDir() (string, error) {
usr, err := user.Current()
if err != nil {
return "", err
}
return usr.HomeDir, nil
}