github.com/viant/toolbox@v0.34.5/data/udf/time.go (about) 1 package udf 2 3 import ( 4 "fmt" 5 "github.com/viant/toolbox" 6 "github.com/viant/toolbox/data" 7 "time" 8 ) 9 10 //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 . 11 func FormatTime(source interface{}, state data.Map) (interface{}, error) { 12 if !toolbox.IsSlice(source) { 13 return nil, fmt.Errorf("unable to run FormatTime: expected %T, but had: %T", []interface{}{}, source) 14 } 15 aSlice := toolbox.AsSlice(source) 16 if len(aSlice) < 2 { 17 return nil, fmt.Errorf("unable to run FormatTime, expected 2 parameters, but had: %v", len(aSlice)) 18 } 19 var err error 20 var timeText = toolbox.AsString(aSlice[0]) 21 var timeFormat = toolbox.AsString(aSlice[1]) 22 var timeLayout = toolbox.DateFormatToLayout(timeFormat) 23 var timeValue *time.Time 24 timeValue, err = toolbox.TimeAt(timeText) 25 if err != nil { 26 timeValue, err = toolbox.ToTime(aSlice[0], timeLayout) 27 } 28 if err != nil { 29 return nil, err 30 } 31 if len(aSlice) > 2 && aSlice[2] != "" { 32 timeLocation, err := time.LoadLocation(toolbox.AsString(aSlice[2])) 33 if err != nil { 34 return nil, err 35 } 36 timeInLocation := timeValue.In(timeLocation) 37 timeValue = &timeInLocation 38 } 39 40 if len(aSlice) > 3 { 41 switch aSlice[3] { 42 case "weekday": 43 return timeValue.Weekday(), nil 44 default: 45 truncFromat := toolbox.DateFormatToLayout(toolbox.AsString(aSlice[3])) 46 if ts, err := time.Parse(truncFromat, timeValue.Format(truncFromat));err == nil { 47 timeValue = &ts 48 } 49 } 50 } 51 52 return timeValue.Format(timeLayout), nil 53 } 54 55 //Elapsed returns elapsed time 56 func Elapsed(source interface{}, state data.Map) (interface{}, error) { 57 inThePast, err := toolbox.ToTime(source, time.RFC3339) 58 if err != nil { 59 return nil, err 60 } 61 elapsed := time.Now().Sub(*inThePast).Truncate(time.Second) 62 63 days := elapsed / (24 * time.Hour) 64 hours := int(elapsed.Hours()) % 24 65 min := int(elapsed.Minutes()) % 60 66 sec := int(elapsed.Seconds()) % 60 67 result := "" 68 if days > 0 { 69 result = fmt.Sprintf("%dd", int(days)) 70 } 71 if result == "" && hours > 0 { 72 result += fmt.Sprintf("%dh", hours) 73 } 74 if result == "" && min > 0 { 75 result += fmt.Sprintf("%dm", min) 76 } 77 result += fmt.Sprintf("%ds", sec) 78 return result, nil 79 80 }