/
magic.go
66 lines (62 loc) · 1.34 KB
/
magic.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
package magic
import (
"fmt"
"strings"
"time"
)
// 渲染魔法变量,获取渲染结果
func GoMagic(rawSql string, now time.Time) (ret string) {
sps := strings.Split(rawSql, "@(") //@(),对于每个分片找右括号
ret = sps[0]
for idx := 1; idx < len(sps); idx++ {
idxr := strings.Index(sps[idx], ")")
if idxr == -1 {
return rawSql
}
ret += convertMagic(sps[idx][0:idxr], now)
if idxr+1 < len(sps[idx]) {
ret += sps[idx][idxr+1:]
}
}
return ret
}
// 支持 YYYY, YY, MM, DD, hh, mm, ss, M, D, h, m, s
func convertMagic(magic string, now time.Time) (ret string) {
switch magic {
case "YYYY":
return fmt.Sprintf("%d", now.Year())
case "YY":
return fmt.Sprintf("%d", now.Year())[2:]
case "MM":
m := int(now.Month())
return fmt.Sprintf("%02d", m)
case "M":
m := int(now.Month())
return fmt.Sprintf("%d", m)
case "D":
d := int(now.Day())
return fmt.Sprintf("%d", d)
case "DD":
d := int(now.Day())
return fmt.Sprintf("%02d", d)
case "hh":
h := now.Hour()
return fmt.Sprintf("%02d", h)
case "h":
h := now.Hour()
return fmt.Sprintf("%d", h)
case "mm":
m := now.Minute()
return fmt.Sprintf("%02d", m)
case "m":
m := now.Minute()
return fmt.Sprintf("%d", m)
case "ss":
s := now.Second()
return fmt.Sprintf("%02d", s)
case "s":
s := now.Second()
return fmt.Sprintf("%d", s)
}
return ""
}