HTTP Date Format And Parse

Format Dates as IMF-fixdate for HTTP headers and parse all three legacy HTTP date formats into Date objects.

JavascriptData Fetching

Code

javascriptsnippet
25 lines
const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

function pad(value) {
  return String(value).padStart(2, "0");
}

export function formatHttpDate(date = new Date()) {
  const value = date instanceof Date ? date : new Date(date);
  if (Number.isNaN(value.getTime())) throw new RangeError("invalid date");
  return DAYS[value.getUTCDay()] + ", "
    + pad(value.getUTCDate()) + " "
    + MONTHS[value.getUTCMonth()] + " "
    + value.getUTCFullYear() + " "
    + pad(value.getUTCHours()) + ":"
    + pad(value.getUTCMinutes()) + ":"
    + pad(value.getUTCSeconds()) + " GMT";
}

export function parseHttpDate(input) {
  if (typeof input !== "string") throw new TypeError("input must be a string");
  const value = Date.parse(input);
  if (Number.isNaN(value)) throw new RangeError("invalid HTTP date");
  return new Date(value);
}

What the code does

Count the functions pad, formatHttpDate and parseHttpDate as the entire surface area of HTTP Date Format And Parse.

Failure is loud: RangeError and TypeError aborts the current operation instead of degrading it.

A fresh value is allocated for the result; the arguments stay untouched.

What to watch for

  • The guard typeof input !== "string" short-circuits the flow with an early throw when its condition holds.

Applying it

The primary signature is export function formatHttpDate(date = new Date()

The surface worth importing is formatHttpDate; the helpers around it are private to the snippet.

Statements that matter

if (typeof input !== "string") throw new TypeError("input must be a string");
if (Number.isNaN(value.getTime())) throw new RangeError("invalid date");
if (Number.isNaN(value)) throw new RangeError("invalid HTTP date");

Interactive Tools for This Topic

FAQ

Does `formatHttpDate` modify its input?
No mutation happens — the function reads its input and returns a new value.
Is there a failure path for bad input?
The code throws `RangeError` and `TypeError` — the guard `typeof input !== "string"` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
Will the snippet run without installing packages?
Yes, it runs as-is — nothing outside the built-in APIs is referenced. The file defines `pad`, `formatHttpDate`, `parseHttpDate` at load time.