-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatemath.go
More file actions
62 lines (52 loc) · 1.58 KB
/
datemath.go
File metadata and controls
62 lines (52 loc) · 1.58 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
package datemath
// Evaluates date math expressions like: [ operator ] [ number ] [ unit ] such
// as "+5w".
//
// Operator is either + or -. Units supported are y (year), M (month), w
// (week), d (day), h (hour), m (minute), and s (second).
import (
"fmt"
"strconv"
"strings"
"time"
)
var zero = time.Time{}
// Eval evaluates a duration relative to now and returns the time or an error.
func Eval(expression string) (time.Time, error) {
return EvalAnchor(time.Now(), expression)
}
// evalAnchor evaluates a date expression relative to an anchor time.
func EvalAnchor(anchor time.Time, expression string) (time.Time, error) {
if len(expression) < 3 {
return zero, fmt.Errorf("Expression too short: %s", expression)
}
if strings.HasPrefix(expression, "now") {
expression = expression[3:]
}
if expression == "" {
return time.Now(), nil
}
numStr, unit := expression[:len(expression)-1], expression[len(expression)-1]
num, err := strconv.Atoi(numStr)
if err != nil {
return zero, fmt.Errorf("Invalid duration `%s` in expression: %s", numStr, expression)
}
switch unit {
case 'y':
return anchor.AddDate(num, 0, 0), nil
case 'M':
return anchor.AddDate(0, num, 0), nil
case 'w':
return anchor.AddDate(0, 0, num*7), nil
case 'd':
return anchor.AddDate(0, 0, num), nil
case 'h':
return anchor.Add(time.Duration(num) * time.Hour), nil
case 'm':
return anchor.Add(time.Duration(num) * time.Minute), nil
case 's':
return anchor.Add(time.Duration(num) * time.Second), nil
default:
return zero, fmt.Errorf("Invalid unit `%s` in expression: %s", string(unit), expression)
}
}