From 32ac017d412a2aec0ce3b52a121da1cc37283054 Mon Sep 17 00:00:00 2001 From: siddharth ravikumar Date: Wed, 20 Jul 2022 23:06:58 -0400 Subject: add `time` package --- time/time.go | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 time/time.go (limited to 'time/time.go') diff --git a/time/time.go b/time/time.go new file mode 100644 index 0000000..97bd3d5 --- /dev/null +++ b/time/time.go @@ -0,0 +1,44 @@ +// Copyright © 2022 siddharth ravikumar +// SPDX-License-Identifier: ISC + +// ISO 8601 utility functions +package time + +import ( + "fmt" + "regexp" + "strconv" +) + +// ISO 8601 Duration regex for matching duration in PT3H4M60S format. +var durationRegex = regexp.MustCompile(`PT(([0-9]{0,2})?H)?(([0-9]{0,2})?M)?(([0-9]{0,2}?)S)?`) + +// Converts ISO 8601 duration[1] to seconds. +// +// Recognizes durations in this format: PT3H4M60S +// +// [1]: https://en.wikipedia.org/wiki/ISO_8601#Durations +func durationToSeconds(duration string) (int, error) { + m := durationRegex.FindStringSubmatch(duration) + if m == nil || len(m) == 0 { + return 0, fmt.Errorf("duration invalid: %v", duration) + } + hours, err := strconv.Atoi(m[2]) + if err != nil { + hours = 0 + } + mins, err := strconv.Atoi(m[4]) + if err != nil { + mins = 0 + } + secs, err := strconv.Atoi(m[6]) + if err != nil { + secs = 0 + } + + // Add 'em all together. + secs += hours * 3600 + secs += mins * 60 + + return secs, nil +} -- cgit v1.2.3