summaryrefslogtreecommitdiffstats
path: root/time
diff options
context:
space:
mode:
authorsiddharth ravikumar <s@ricketyspace.net>2022-08-13 13:17:47 -0400
committersiddharth ravikumar <s@ricketyspace.net>2022-08-13 13:18:45 -0400
commitc4b3abd12e75645fef7d7aa8a460972e761458fb (patch)
tree37839bc089474626cc4890b6a85119f4647ac7b9 /time
parent6751d139ff328fb9852b6df5e014c38389803206 (diff)
time: update `Duration`
Add handling for parsing days.
Diffstat (limited to 'time')
-rw-r--r--time/time.go17
-rw-r--r--time/time_test.go20
2 files changed, 31 insertions, 6 deletions
diff --git a/time/time.go b/time/time.go
index 89847ab..d22df3b 100644
--- a/time/time.go
+++ b/time/time.go
@@ -12,12 +12,12 @@ import (
"time"
)
-// 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)?`)
+// ISO 8601 Duration regex for matching duration in P18DT3H4M60S format.
+var durationRegex = regexp.MustCompile(`P(([0-9]{1,})?D)?T(([0-9]{1,2})?H)?(([0-9]{1,2})?M)?(([0-9]{1,2}?)S)?`)
// Converts ISO 8601 duration[1] to time.Duration
//
-// Recognizes durations in this format: PT3H4M60S
+// Recognizes durations in this format: P18DT3H4M60S
//
// [1]: https://en.wikipedia.org/wiki/ISO_8601#Durations
func Duration(duration string) (time.Duration, error) {
@@ -25,20 +25,25 @@ func Duration(duration string) (time.Duration, error) {
if m == nil || len(m) == 0 {
return 0, fmt.Errorf("duration invalid: %v", duration)
}
- hours, err := strconv.Atoi(m[2])
+ days, err := strconv.Atoi(m[2])
+ if err != nil {
+ days = 0
+ }
+ hours, err := strconv.Atoi(m[4])
if err != nil {
hours = 0
}
- mins, err := strconv.Atoi(m[4])
+ mins, err := strconv.Atoi(m[6])
if err != nil {
mins = 0
}
- secs, err := strconv.Atoi(m[6])
+ secs, err := strconv.Atoi(m[8])
if err != nil {
secs = 0
}
// Add 'em all together.
+ secs += days * 86400
secs += hours * 3600
secs += mins * 60
diff --git a/time/time_test.go b/time/time_test.go
index efb3078..3f0bb84 100644
--- a/time/time_test.go
+++ b/time/time_test.go
@@ -69,6 +69,26 @@ func TestDurationToSeconds(t *testing.T) {
t.Errorf("duration in seconds incorrect: %v", d)
return
}
+
+ d, err = Duration("P3DT45M")
+ if err != nil {
+ t.Errorf("failed: %v", err)
+ return
+ }
+ if d.Seconds() != 261900 {
+ t.Errorf("duration in seconds incorrect: %v", d)
+ return
+ }
+
+ d, err = Duration("P7DT18H")
+ if err != nil {
+ t.Errorf("failed: %v", err)
+ return
+ }
+ if d.Seconds() != 669600 {
+ t.Errorf("duration in seconds incorrect: %v", d)
+ return
+ }
}
func TestIsCurrent(t *testing.T) {