Last active
May 12, 2024 02:23
-
-
Save spatialtime/2a54a6dbf80121997b2459b2d3b9b380 to your computer and use it in GitHub Desktop.
Golang and ISO 8601 durations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This snippet demonstrates Golang formatting and parsing of ISO 8601 durations. | |
// A little work is required to navigate between Golang's | |
// duration syntax and ISO 8601 duration syntax. | |
import ( | |
"errors" | |
"fmt" | |
"regexp" | |
"strings" | |
"time" | |
) | |
// ParseDuration parses an ISO 8601 string representing a duration, | |
// and returns the resultant golang time.Duration instance. | |
func ParseDuration(isoDuration string) (time.Duration, error) { | |
re := regexp.MustCompile(`^P(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)D)?T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:.\d+)?)S)?$`) | |
matches := re.FindStringSubmatch(isoDuration) | |
if matches == nil { | |
return 0, errors.New("input string is of incorrect format") | |
} | |
seconds := 0.0 | |
//skipping years and months | |
//days | |
if matches[3] != "" { | |
f, err := strconv.ParseFloat(matches[3], 32) | |
if err != nil { | |
return 0, err | |
} | |
seconds += (f * 24 * 60 * 60) | |
} | |
//hours | |
if matches[4] != "" { | |
f, err := strconv.ParseFloat(matches[4], 32) | |
if err != nil { | |
return 0, err | |
} | |
seconds += (f * 60 * 60) | |
} | |
//minutes | |
if matches[5] != "" { | |
f, err := strconv.ParseFloat(matches[5], 32) | |
if err != nil { | |
return 0, err | |
} | |
seconds += (f * 60) | |
} | |
//seconds & milliseconds | |
if matches[6] != "" { | |
f, err := strconv.ParseFloat(matches[6], 32) | |
if err != nil { | |
return 0, err | |
} | |
seconds += f | |
} | |
goDuration := strconv.FormatFloat(seconds, 'f', -1, 32) + "s" | |
return time.ParseDuration(goDuration) | |
} | |
// FormatDuration returns an ISO 8601 duration string. | |
func FormatDuration(dur time.Duration) string { | |
return "PT" + strings.ToUpper(dur.Truncate(time.Millisecond).String()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is buggy as hell:
P20D
wouldn't parse despite being correct formatThis is more correct format. Still lazy though as it shouldn't allow only
P
,PT
or time separator without time^P(?:(\\d+)Y)?(?:(\\d+)M)?(?:(\\d+)W)?(?:(\\d+)D)?(?:T(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)S)?)?$