To format a JavaScript Date object as a YYYYMMDD string, extract the year, month, and day components using either local time (getFullYear(), getMonth() + 1, getDate()) or UTC (getUTCFullYear(), getUTCMonth() + 1, getUTCDate()), zero-pad the month and day to two digits with String.prototype.padStart(2, "0"), and concatenate them without separators. Using explicit component getters avoids time-zone shifts and locale slash/dash formatting quirks found in toISOString() or toLocaleDateString().
1. Formatting a Date in Local Time (YYYYMMDD)
When you want the calendar date in the user’s or runtime’s local time zone, read the local getters, add 1 to the zero-based month, and pad two-digit fields with padStart(2, "0"):
// Format a Date instance as "YYYYMMDD" using local time
function formatDateYYYYMMDD(date) {
if (!(date instanceof Date) || Number.isNaN(date.getTime())) {
throw new TypeError("Expected a valid Date instance.");
}
const year = String(date.getFullYear());
const month = String(date.getMonth() + 1).padStart(2, "0");
const day = String(date.getDate()).padStart(2, "0");
return `${year}${month}${day}`;
}
// Example usage:
const sampleDate = new Date(2026, 2, 5); // March 5, 2026 (month is 0-indexed)
console.log(formatDateYYYYMMDD(sampleDate)); // "20260305"
- Zero-based month (
0–11):getMonth()returns0for January through11for December, so always add1before padding. - Invalid
Dateguard: CheckingNumber.isNaN(date.getTime())catches invalid dates likenew Date("invalid")early.
2. Formatting a Date in UTC (YYYYMMDD)
When working with timestamps, logs, or backend dates that must stay anchored to Coordinated Universal Time regardless of local offsets, use the getUTC* methods instead:
// Format a Date instance as "YYYYMMDD" in UTC
function formatDateUTCYYYYMMDD(date) {
if (!(date instanceof Date) || Number.isNaN(date.getTime())) {
throw new TypeError("Expected a valid Date instance.");
}
const year = String(date.getUTCFullYear());
const month = String(date.getUTCMonth() + 1).padStart(2, "0");
const day = String(date.getUTCDate()).padStart(2, "0");
return `${year}${month}${day}`;
}
// Example usage:
const lateUtc = new Date("2026-11-29T23:30:00Z");
console.log(formatDateUTCYYYYMMDD(lateUtc)); // "20261129"
- Avoids local day rollover bugs: A UTC timestamp near midnight can belong to different calendar days in UTC versus local time.
- Years before
1000: If historical years under four digits are possible, padyearwithpadStart(4, "0")as well.
3. Why Not toISOString().slice(0, 10).replaceAll("-", "")?
Slicing toISOString() is a common shorthand, but it always converts to UTC first, which can shift the date backward or forward relative to local time:
// Caveat: toISOString() always uses UTC, not local time
const localMidnight = new Date(2026, 10, 29, 0, 30, 0); // Nov 29, 2026 00:30 local
const isoDate = localMidnight.toISOString().slice(0, 10).replaceAll("-", "");
console.log(formatDateYYYYMMDD(localMidnight)); // Local calendar day
console.log(isoDate); // UTC calendar day (may differ)
- Explicit is safer: Calling
getFullYear()orgetUTCFullYear()makes your time-zone intent unmistakable in code reviews. - Pure string formatting: Returning a string preserves leading zeros on months (
01–09) and days (01–09).
TL;DR: Format a Date as YYYYMMDD by combining getFullYear() (or getUTCFullYear()), String(getMonth() + 1).padStart(2, "0"), and String(getDate()).padStart(2, "0") after validating !Number.isNaN(date.getTime()).
