File: time.go

package info (click to toggle)
golang-github-viant-toolbox 0.33.2-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 1,280 kB
  • sloc: makefile: 16
file content (80 lines) | stat: -rw-r--r-- 2,254 bytes parent folder | download | duplicates (2)
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
package udf

import (
	"fmt"
	"github.com/viant/toolbox"
	"github.com/viant/toolbox/data"
	"time"
)

//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)
	}
	aSlice := toolbox.AsSlice(source)
	if len(aSlice) < 2 {
		return nil, fmt.Errorf("unable to run FormatTime, expected 2 parameters, but had: %v", len(aSlice))
	}
	var err error
	var timeText = toolbox.AsString(aSlice[0])
	var timeFormat = toolbox.AsString(aSlice[1])
	var timeLayout = toolbox.DateFormatToLayout(timeFormat)
	var timeValue *time.Time
	timeValue, err = toolbox.TimeAt(timeText)
	if err != nil {
		timeValue, err = toolbox.ToTime(aSlice[0], timeLayout)
	}
	if err != nil {
		return nil, err
	}
	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 {
		switch aSlice[3] {
		case "weekday":
			return timeValue.Weekday(), nil
		default:
			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
}

//Elapsed returns elapsed time
func Elapsed(source interface{}, state data.Map) (interface{}, error) {
	inThePast, err := toolbox.ToTime(source, time.RFC3339)
	if err != nil {
		return nil, err
	}
	elapsed := time.Now().Sub(*inThePast).Truncate(time.Second)

	days := elapsed / (24 * time.Hour)
	hours := int(elapsed.Hours()) % 24
	min := int(elapsed.Minutes()) % 60
	sec := int(elapsed.Seconds()) % 60
	result := ""
	if days > 0 {
		result = fmt.Sprintf("%dd", int(days))
	}
	if result == "" && hours > 0 {
		result += fmt.Sprintf("%dh", hours)
	}
	if result == "" && min > 0 {
		result += fmt.Sprintf("%dm", min)
	}
	result += fmt.Sprintf("%ds", sec)
	return result, nil

}