summaryrefslogtreecommitdiffstats
path: root/time/time.go
blob: 97bd3d53e10131a1795c4ad4ee716efc6db78b84 (plain) (blame)
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
// Copyright © 2022 siddharth ravikumar <s@ricketyspace.net>
// 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
}