logo hsb.horse
← Back to snippets index

Snippets

Time-Based Semantic Version Generation

A TypeScript function that automatically generates version numbers from build timestamps. Useful when version limits exist, such as in Chrome extensions.

Published: Updated:

There are times when you want to use the build or deployment timestamp directly as the version number, rather than incremental versioning. This is particularly relevant for Chrome extensions, where the maximum version value is limited to 65535, requiring proper conversion of timestamps.

Code

type SemanticVersion = `${string}.${string}.${string}`;
function timeBasedSemanticVersion(): SemanticVersion {
const now = new Date();
const major = now.getFullYear();
// Use top two digits for month, bottom two for day
const minor = `${(now.getMonth() + 1) * 100 + now.getDate()}`;
const hh = `${now.getHours()}`;
const mm = `${now.getMinutes()}`.padStart(2, "0");
const s = `${now.getSeconds()}`.slice(-1);
const patch = `${hh}${mm}${s}`;
return `${major}.${minor}.${patch}`;
}

Usage Example

console.log(timeBasedSemanticVersion());
// 2026.0214.14305 (for February 14, 2026 at 14:30:50)

Specification

  • major: Year (YYYY) - e.g., 2026
  • minor: Month and day (MMDD) - e.g., 0214. Max is 1231, so it stays within the 65535 limit
  • patch: Hours, minutes, and last digit of seconds (hhmms) - e.g., 14305. Max is 23595, so it stays within the limit

Prerelease tags and build metadata are not supported. This is not pure SemVer, but rather a format that encodes timestamps in a readable way.

Alternative Approaches

The issue with this approach is that if the time goes backward during multiple builds on the same day, the version number could decrease. For stricter management, consider the following:

  • Shortened git commit hash (high uniqueness but loses time information)
  • CI/CD build number (sequential but provider-dependent)
  • Combination of date-time and build number

The advantage of the timestamp-based approach is that the build time is immediately visible. This is effective for debugging and troubleshooting.