Skip to content

Commit

Permalink
fix: parse both unix int and RFC3339 string in toUnixTimestamp
Browse files Browse the repository at this point in the history
Signed-off-by: Prashant Shahi <[email protected]>
  • Loading branch information
prashant-shahi committed May 29, 2024
1 parent 1db1f76 commit 7ea1bca
Showing 1 changed file with 14 additions and 5 deletions.
19 changes: 14 additions & 5 deletions pkg/query-service/postprocess/formula.go
Original file line number Diff line number Diff line change
Expand Up @@ -266,18 +266,27 @@ func EvalFuncs() map[string]govaluate.ExpressionFunction {
GoValuateFuncs["radians"] = func(args ...interface{}) (interface{}, error) {
return args[0].(float64) * math.Pi / 180, nil
}

// Returns the current Unix timestamp in seconds.
GoValuateFuncs["now"] = func(args ...interface{}) (interface{}, error) {
return time.Now().Unix(), nil
}

// Returns the given timestamp in seconds. The argument can be a string in RFC3339 format or an int in seconds since Unix epoch.
GoValuateFuncs["toUnixTimestamp"] = func(args ...interface{}) (interface{}, error) {
if len(args) != 1 {
return nil, fmt.Errorf("toUnixTimestamp requires exactly one argument")
}
t, err := time.Parse(time.RFC3339, args[0].(string))
if err != nil {
return nil, err
var t time.Time
var err error
switch toUnixTsArg := args[0].(type) {
case int:
t = time.Unix(int64(toUnixTsArg), 0)
case string:
t, err = time.Parse(time.RFC3339, toUnixTsArg)
if err != nil {
return nil, err
}
default:
return nil, fmt.Errorf("toUnixTimestamp requires either a string in RFC3339 format or an int in seconds since Unix epoch")
}
return t.Unix(), nil
}
Expand Down

0 comments on commit 7ea1bca

Please sign in to comment.