Go's time.Sub in TypeScript

✓ Verified: Go 1.23
Examples tested against actual runtime. CI re-verifies continuously. Only documented examples are tested.

How to use

Install via yarn add locutus and import: import { Sub } from 'locutus/golang/time/Sub'.

Or with CommonJS: const { Sub } = require('locutus/golang/time/Sub')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1Sub('2026-03-03T13:14:15.500Z', '2026-03-03T13:14:15.000Z')500
2Sub('2026-03-03T13:14:10.000Z', '2026-03-03T13:14:15.000Z')-5000

Notes

  • Returns the duration in milliseconds between two instants (left - right).

Here's what our current TypeScript equivalent to Go's time.Sub looks like.

type GoTimeInput = Date | string | number

const toTimeDate = (value: GoTimeInput): Date => {
const date = value instanceof Date ? new Date(value.getTime()) : new Date(value)
if (Number.isNaN(date.getTime())) {
throw new TypeError('Sub(): invalid date input')
}
return date
}

export function Sub(left: GoTimeInput, right: GoTimeInput): number {
// discuss at: https://locutus.io/golang/time/Sub
// parity verified: Go 1.23
// original by: Kevin van Zonneveld (https://kvz.io)
// note 1: Returns the duration in milliseconds between two instants (left - right).
// example 1: Sub('2026-03-03T13:14:15.500Z', '2026-03-03T13:14:15.000Z')
// returns 1: 500
// example 2: Sub('2026-03-03T13:14:10.000Z', '2026-03-03T13:14:15.000Z')
// returns 2: -5000

return toTimeDate(left).getTime() - toTimeDate(right).getTime()
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


We have 47 Go functions so far - help us add more

Got a rainy Sunday afternoon and a taste for a porting puzzle?

We will then review it. If it's useful to the project and in line with our contributing guidelines your work will become part of Locutus and you'll be automatically credited in the authors section accordingly.


« More Go time functions


Star