Skip to content

Commit

Permalink
added trunc option for FormatTime udf
Browse files Browse the repository at this point in the history
  • Loading branch information
adranwit committed Feb 6, 2020
1 parent 0865482 commit 2a4ef0b
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
## Feb 6 2020 - v0.29.5
- Added data.udf.FormatTime with trunc parameter
- Added cred.Config.Endpoint
## October 9 - v0.29.0
- Added data.udf.Replace

Expand Down
12 changes: 10 additions & 2 deletions data/udf/time.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
"time"
)

//FormatTime return formatted time, it takes an array of two arguments, the first id time, or now followed by java style time format.
//FormatTime return formatted time, it takes an array of arguments, the first is time express, or now followed by java style time format, optional timezone and truncate format .
func FormatTime(source interface{}, state data.Map) (interface{}, error) {
if !toolbox.IsSlice(source) {
return nil, fmt.Errorf("unable to run FormatTime: expected %T, but had: %T", []interface{}{}, source)
Expand All @@ -28,14 +28,22 @@ func FormatTime(source interface{}, state data.Map) (interface{}, error) {
if err != nil {
return nil, err
}
if len(aSlice) > 2 {
if len(aSlice) > 2 && aSlice[2] != "" {
timeLocation, err := time.LoadLocation(toolbox.AsString(aSlice[2]))
if err != nil {
return nil, err
}
timeInLocation := timeValue.In(timeLocation)
timeValue = &timeInLocation
}

if len(aSlice) > 3 {
truncFromat := toolbox.DateFormatToLayout(toolbox.AsString(aSlice[3]))
if ts, err := time.Parse(truncFromat, timeValue.Format(truncFromat));err == nil {
timeValue = &ts
}
}

return timeValue.Format(timeLayout), nil
}

Expand Down
10 changes: 10 additions & 0 deletions data/udf/time_test.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package udf

import (
"fmt"
"github.com/stretchr/testify/assert"
"github.com/viant/toolbox"
"github.com/viant/toolbox/data"
"strings"
"testing"
"time"
)
Expand Down Expand Up @@ -48,6 +50,14 @@ func Test_FormatTime(t *testing.T) {
assert.Equal(t, "2015", expanded)
}

{
value, err := FormatTime([]interface{}{"now", "yyyy-MM-dd hh:mm:ss", "", "yyyy-MM"}, nil)
fmt.Printf("value: %v\n", value)
assert.Nil(t, err)
now := time.Now()
assert.True(t, strings.HasPrefix(toolbox.AsString(value), toolbox.AsString(now.Year())))
}

}

func TestElapsed(t *testing.T) {
Expand Down

0 comments on commit 2a4ef0b

Please sign in to comment.