JavaScript Date Formatting Cheat Sheet

JavaScript has a messy date library. It's mutability and zero indexed months can make it tough to write correct date manipulation code. So here's my cheat sheet for formatting JavaScript dates and times:

// -----------------------------------------------
// 1. ISO 8601 (YYYY-MM-DD)
// -----------------------------------------------
new Date(1998, 0, 7).toISOString().split('T')[0];
// => "1998-01-07"

// -----------------------------------------------
// 2. American date (MM/DD/YYYY)
// -----------------------------------------------
new Date(1998, 6, 8).toLocaleDateString('en-US');
// => "7/8/1998"

// -----------------------------------------------
// 3. American date with 2 digit day (MM/DD/YYYY)
// -----------------------------------------------
new Date(1998, 6, 8).toLocaleDateString('en-US', {
    month: 'numeric',
    day: '2-digit',
    year: 'numeric',
});
// => "7/08/1998"

// -----------------------------------------------
// 4. Date with full month name (MONTH DAY, YEAR)
// -----------------------------------------------
new Date(1998, 8, 31).toLocaleDateString('en-US', {
    month: 'long',
    day: 'numeric',
    year: 'numeric',
});
// => "October 1, 1998"

// -----------------------------------------------
// 5. Time of day with meridian (H:MM [meridian])
// -----------------------------------------------
new Date().toLocaleTimeString(
    'en-US',
    {
        hour: 'numeric',
        minute: '2-digit',
        meridian: true,
    }
);
// => "9:05 PM"

// -----------------------------------------------
// 6. 24 hour time of day
// -----------------------------------------------
new Date().toLocaleTimeString(
    'en-US',
    {
        hour12: false,
        hour: 'numeric',
        minute: '2-digit',
    }
);
// => "21:05"