Skip to content

time.Duration workaround using javascript. #72

@figuerom16

Description

@figuerom16

Sorry this isn't an issue so much as a work around for time.Duration (int64) using Javascript.
You can do progressive form enhancement on the client and convert a golang time.Duration string to nanoseconds using the below function.

const NANO_MULTIPLIERS = {
	ns: 1,
	us: 1000,
	ms: 1000 * 1000,
	s: 1000 * 1000 * 1000,
	m: 60 * 1000 * 1000 * 1000,
	h: 60 * 60 * 1000 * 1000 * 1000,
}

function durationToNanos(durationString) {// This is golang specific. eg. 72h30m1s100ms10us5ns
	if (!durationString) return 0
	let totalNanoseconds = 0
	let lastIndex = 0
	const matches = [...durationString.matchAll(/(\d+)(ns|us|ms|s|m|h)/g)]
	if (matches.length === 0 && durationString.length > 0) throw new Error(`Invalid duration string format: "${durationString}"`)
	for (const match of matches) {
		totalNanoseconds += parseInt(match[1], 10) * NANO_MULTIPLIERS[match[2]]
		lastIndex = match.index + match[0].length
	}
	if (lastIndex !== durationString.length) throw new Error(`Invalid characters found in duration string: "${durationString}"`)
	return totalNanoseconds
}

Hopefully someone finds this useful in the future.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions