MCPcopy
hub / github.com/spf13/cast / ToDurationE

Function ToDurationE

time.go:64–101  ·  view source on GitHub ↗

ToDurationE casts any value to a [time.Duration] type.

(i any)

Source from the content-addressed store, hash-verified

62
63// ToDurationE casts any value to a [time.Duration] type.
64func ToDurationE(i any) (time.Duration, error) {
65 i, _ = indirect(i)
66
67 switch s := i.(type) {
68 case time.Duration:
69 return s, nil
70 case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
71 v, err := ToInt64E(s)
72 if err != nil {
73 // TODO: once there is better error handling, this should be easier
74 return 0, errors.New(strings.ReplaceAll(err.Error(), " int64", "time.Duration"))
75 }
76
77 return time.Duration(v), nil
78 case float32, float64, float64EProvider, float64Provider:
79 v, err := ToFloat64E(s)
80 if err != nil {
81 // TODO: once there is better error handling, this should be easier
82 return 0, errors.New(strings.ReplaceAll(err.Error(), " float64", "time.Duration"))
83 }
84
85 return time.Duration(v), nil
86 case string:
87 if !strings.ContainsAny(s, "nsuµmh") {
88 return time.ParseDuration(s + "ns")
89 }
90
91 return time.ParseDuration(s)
92 case nil:
93 return time.Duration(0), nil
94 default:
95 if i, ok := resolveAlias(i); ok {
96 return ToDurationE(i)
97 }
98
99 return 0, fmt.Errorf(errorMsg, i, i, time.Duration(0))
100 }
101}
102
103// StringToDate attempts to parse a string into a [time.Time] type using a
104// predefined list of formats.

Callers 2

ToDurationFunction · 0.85
ToEFunction · 0.85

Calls 5

indirectFunction · 0.85
ToInt64EFunction · 0.85
ToFloat64EFunction · 0.85
resolveAliasFunction · 0.85
ErrorMethod · 0.80

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…