a1284075aa
Validate constructors, strict HH:MM:SS parse, UTC ClockTimeFromTime, ISODuration Value/Scan, Compare and TextMarshaler, codec.go split. Co-authored-by: Cursor <cursoragent@cursor.com>
50 lines
1.3 KiB
Go
50 lines
1.3 KiB
Go
package clocktime
|
|
|
|
import (
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/sosodev/duration"
|
|
)
|
|
|
|
// ISODuration wraps time.Duration with ISO 8601 string formatting.
|
|
type ISODuration time.Duration
|
|
|
|
// NewISODuration creates a duration from hour, minute, and second components.
|
|
func NewISODuration(hours, minutes, seconds int) ISODuration {
|
|
return ISODuration(
|
|
time.Hour*time.Duration(hours) +
|
|
time.Minute*time.Duration(minutes) +
|
|
time.Second*time.Duration(seconds),
|
|
)
|
|
}
|
|
|
|
// ParseISODuration parses an ISO 8601 duration string (for example PT1H30M).
|
|
func ParseISODuration(s string) (ISODuration, error) {
|
|
return DurationFromISOString(s)
|
|
}
|
|
|
|
// DurationFromISOString parses an ISO 8601 duration string.
|
|
func DurationFromISOString(s string) (ISODuration, error) {
|
|
d, err := duration.Parse(s)
|
|
if err != nil {
|
|
return 0, fmt.Errorf("error parsing ISO 8601 duration: %w", err)
|
|
}
|
|
return ISODuration(d.ToTimeDuration()), nil
|
|
}
|
|
|
|
// ISODurationFromDuration converts a time.Duration to ISODuration.
|
|
func ISODurationFromDuration(d time.Duration) ISODuration {
|
|
return ISODuration(d)
|
|
}
|
|
|
|
// String returns the ISO 8601 representation.
|
|
func (d ISODuration) String() string {
|
|
return duration.FromTimeDuration(time.Duration(d)).String()
|
|
}
|
|
|
|
// Duration returns the underlying time.Duration.
|
|
func (d ISODuration) Duration() time.Duration {
|
|
return time.Duration(d)
|
|
}
|