use tinyduration for ISO8601 parsing and serializing

This commit is contained in:
Elijah Duffy
2025-12-11 20:40:27 -08:00
parent 837029b598
commit ae3abad769
3 changed files with 17 additions and 21 deletions

View File

@@ -26,12 +26,7 @@
* @returns The ISO 8601 duration string.
*/
export const durationToISO8601 = (duration: TimeDuration): string => {
let str = 'P';
if (duration.hours || duration.minutes || duration.seconds) str += 'T';
if (duration.hours) str += `${duration.hours}H`;
if (duration.minutes) str += `${duration.minutes}M`;
if (duration.seconds) str += `${duration.seconds}S`;
return str;
return serialize(duration);
};
/**
@@ -40,16 +35,7 @@
* @returns The TimeDuration object.
*/
export const iso8601ToDuration = (str: string): TimeDuration => {
const regex = /^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/;
const matches = str.match(regex);
if (!matches) {
throw new Error('Invalid ISO 8601 duration string');
}
return {
hours: matches[2] ? parseInt(matches[2], 10) : 0,
minutes: matches[3] ? parseInt(matches[3], 10) : 0,
seconds: matches[4] ? parseInt(matches[4], 10) : 0
};
return parse(str);
};
</script>
@@ -62,6 +48,7 @@
import Label from './Label.svelte';
import { liveValidator, validate } from '@svelte-toolkit/validate';
import StyledRawInput from './StyledRawInput.svelte';
import { parse, serialize } from 'tinyduration';
interface Props {
/**