HTTP Date Format And Parse
Format Dates as IMF-fixdate for HTTP headers and parse all three legacy HTTP date formats into Date objects.
Code
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);
}Report a problem with this exampleOpens a pre-filled issue on GitHub.