-
Notifications
You must be signed in to change notification settings - Fork 0
/
diff.go
91 lines (79 loc) · 1.83 KB
/
diff.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package DateTimeMate
import (
"fmt"
"github.com/golang-module/carbon/v2"
"github.com/hako/durafmt"
"github.com/tkuchiki/parsetime"
"time"
)
type Diff struct {
Start string
End string
Brief bool
}
type OptionsDiff func(*Diff)
func NewDiff(options ...OptionsDiff) *Diff {
diff := &Diff{}
for _, opt := range options {
opt(diff)
}
return diff
}
func DiffWithStart(start string) OptionsDiff {
return func(opt *Diff) {
opt.Start = start
}
}
func DiffWithEnd(end string) OptionsDiff {
return func(opt *Diff) {
opt.End = end
}
}
func DiffWithBrief(brief bool) OptionsDiff {
return func(opt *Diff) {
opt.Brief = brief
}
}
func (diff *Diff) String() string {
return fmt.Sprintf("Start:%v End:%v Brief:%v", diff.Start, diff.End, diff.Brief)
}
// CalculateDiff return the time difference and also set dt.Diff
// first try to parse with carbon, fallback to parsing with parsetime if carbon fails to parse
func (diff *Diff) CalculateDiff() (string, time.Duration, error) {
var start, end time.Time
alpha := carbon.Parse(ConvertRelativeDateToActual(diff.Start))
if alpha.Error != nil {
// fmt.Println("alpha:", alpha.Error)
p, err := parsetime.NewParseTime()
if err != nil {
return "", 0, err
}
start, err = p.Parse(diff.Start)
if err != nil {
return "", 0, err
}
} else {
start = alpha.StdTime()
}
omega := carbon.Parse(ConvertRelativeDateToActual(diff.End))
if omega.Error != nil {
// fmt.Println("omega:", omega.Error)
p, err := parsetime.NewParseTime()
if err != nil {
return "", 0, err
}
end, err = p.Parse(diff.End)
if err != nil {
return "", 0, err
}
} else {
end = omega.StdTime()
}
duration := end.Sub(start)
parsed := durafmt.Parse(duration)
difference := fmt.Sprintf("%v", parsed)
if diff.Brief {
difference = shrinkPeriod(difference)
}
return difference, duration, nil
}