Functional Weave
Code in Rust

time.unix-to-iso@1.0.0

impl/typescript.ts

1,072 bytes · the TypeScript implementation · view raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

import { isoFromEpochDay } from "./dates_add_days.ts";  ← from dates.add-days ^1.0.0 · built alongside by fune

/** 0001-01-01T00:00:00Z and 9999-12-31T23:59:59Z in Unix seconds. */
const MIN_SECONDS = -62135596800;
const MAX_SECONDS = 253402300799;

function two(n: number): string {
  return n < 10 ? "0" + n : String(n);
}

/**
 * Unix seconds as YYYY-MM-DDTHH:MM:SSZ. The day is floored, so a negative
 * time falls on the day before the epoch rather than rounding towards it.
 */
export function unixToIso(seconds: number): string {
  if (typeof seconds !== "number" || !Number.isInteger(seconds)) {
    throw new TypeError(`seconds must be a whole number, received ${seconds}`);
  }
  if (seconds < MIN_SECONDS || seconds > MAX_SECONDS) {
    throw new RangeError(`seconds must be from ${MIN_SECONDS} to ${MAX_SECONDS} (years 0001 to 9999), received ${seconds}`);
  }
  const day = Math.floor(seconds / 86400);
  const rest = seconds - day * 86400;
  const h = Math.floor(rest / 3600);
  const m = Math.floor((rest % 3600) / 60);
  const s = rest % 60;
  return `${isoFromEpochDay(day)}T${two(h)}:${two(m)}:${two(s)}Z`;
}