Question

How to Format a Date in JavaScript

javascriptdatedatetimedatetime-formatdate-formatting

Question

How can I convert a JavaScript Date object into a formatted string, preferably in a format like 10-Aug-2010?

Short Answer

By the end of this page, you will understand how JavaScript Date objects work, why date formatting often requires custom code, and how to produce readable strings such as 10-Aug-2010 using beginner-friendly JavaScript techniques.

Concept

JavaScript stores dates as Date objects, but a Date object is not automatically displayed in the exact format you want.

For example, this code creates a date:

const date = new Date();

But if you print it directly, JavaScript gives a full date-time string, not a custom format like 10-Aug-2010.

console.log(date);

To get a specific output format, you usually need to:

  • extract the day
  • extract the month
  • extract the year
  • convert the month number into a short month name
  • join the pieces into one string

This matters because date formatting is common in real programs:

  • showing dates in dashboards
  • displaying timestamps in UI
  • exporting reports
  • generating filenames
  • formatting API data for users

A key beginner lesson is that JavaScript's Date object stores date information, while formatting is the job of your code or a formatting API such as Intl.DateTimeFormat.

Mental Model

Think of a Date object like a box containing date parts:

  • day
  • month
  • year
  • time
  • timezone

If you want a string like 10-Aug-2010, you open the box, take out the parts you need, and arrange them in your preferred order.

It is similar to filling out a label:

  • take the day number
  • replace the month number with a readable name
  • add the year
  • connect them with -

So the main idea is: a Date object holds the information, and formatting decides how to present it.

Take Quiz

Syntax and Examples

The most beginner-friendly way is to manually build the string.

Basic syntax

const date = new Date(2010, 7, 10); // 10 August 2010

const months = [
  "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];

const day = date.getDate();
const month = months[date.getMonth()];
const year = date.getFullYear();

const formatted = `${day}-${month}-${year}`;
console.log(formatted); // 10-Aug-2010

Why this works

  • getDate() returns the day of the month
  • getMonth() returns a month index from 0 to 11
  • getFullYear() returns the 4-digit year
  • the months array converts month numbers into names like Aug

Example with leading zero for single-digit days

If you want 05-Aug-2010 instead of 5-Aug-2010, use padStart():

const date = new Date(2010, 7, 5);

const months = [
  "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];

const day = String(date.getDate()).padStart(2, "0");
const month = months[date.getMonth()];
const year = date.getFullYear();

const formatted = `${day}-${month}-${year}`;
console.log(formatted); // 05-Aug-2010

Using Intl.DateTimeFormat

Modern JavaScript also provides built-in international formatting:

const date = new Date(2010, 7, 10);

const formatter = new Intl.DateTimeFormat("en-GB", {
  day: "2-digit",
  month: "short",
  year: "numeric"
});

console.log(formatter.format(date));

This is useful, but the exact punctuation and spacing can vary by locale, so manual formatting is often best when you need an exact result like 10-Aug-2010.

Step by Step Execution

Consider this example:

const date = new Date(2010, 7, 10);
const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

const day = String(date.getDate()).padStart(2, "0");
const month = months[date.getMonth()];
const year = date.getFullYear();

const formatted = `${day}-${month}-${year}`;
console.log(formatted);

Step by step:

  1. new Date(2010, 7, 10) creates a date.

    • Year = 2010
    • Month = 7
    • Day = 10
  2. The month is 7, but JavaScript months are zero-based:

    • 0 = January
    • 7 = August
  3. date.getDate() returns 10.

  4. String(...).padStart(2, "0") turns 10 into a 2-character string.

    • 10 stays 10
    • if it were 5, it would become 05
  5. date.getMonth() returns 7.

  6. months[7] gives "Aug".

  7. date.getFullYear() returns 2010.

  8. Template literals combine the pieces:

    • 10
    • Aug
    • 2010
  9. Final result:

10-Aug-2010

This is a good example of turning raw data into a user-friendly display string.

Real World Use Cases

Date formatting appears in many practical situations:

User interfaces

  • Showing account creation dates
  • Displaying blog post publish dates
  • Rendering invoice dates
const publishedAt = new Date(2024, 2, 14);
console.log(`${publishedAt.getDate()}-${publishedAt.getMonth()}-${publishedAt.getFullYear()}`);

Reports and exports

  • CSV exports with readable dates
  • PDF report headers
  • generated filenames

Example filename:

const date = new Date();
const fileDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
console.log(`report-${fileDate}.csv`);

API data presentation

APIs often send ISO date strings like 2024-06-01T10:30:00Z. Your frontend may need to convert them into user-friendly text.

const apiDate = new Date("2024-06-01T10:30:00Z");

Logs and notifications

  • Showing when an event happened
  • Formatting timestamps in messages
  • displaying deadlines or reminders
Take Quiz

Real Codebase Usage

In real projects, developers usually do more than just call getDate().

Common patterns

Small formatting helper function

Instead of repeating the same code everywhere, teams often create a reusable function:

function formatDate(date) {
  const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
  const day = String(date.getDate()).padStart(2, "0");
  const month = months[date.getMonth()];
  const year = date.getFullYear();
  return `${day}-${month}-${year}`;
}

Validation before formatting

Developers often guard against invalid dates:

function formatDate(date) {
  if (!(date instanceof Date) || isNaN(date)) {
    return "Invalid date";
  }

  const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
  const day = String(date.getDate()).padStart(2, "0");
  const month = months[date.getMonth()];
  const year = date.getFullYear();

  return `${day}-${month}-${year}`;
}

Early return pattern

This keeps code readable when input might be missing:

function formatDate(date) {
  if (!date) return "";
  if (!(date instanceof Date) || isNaN(date)) return "Invalid date";

  const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
  return `${String(date.getDate()).padStart(2, "0")}-${months[date.getMonth()]}-${date.getFullYear()}`;
}

Formatting lists of dates

Developers often use map() to format arrays of dates:

const dates = [new Date(2010, 7, 10), new Date(2011, 0, 5)];
const formattedDates = dates.map(formatDate);
console.log(formattedDates);

This is common in tables, dashboards, and API response processing.

Common Mistakes

1. Forgetting that months are zero-based

This is one of the most common JavaScript date mistakes.

const date = new Date(2010, 8, 10);
console.log(date);

Many beginners expect August, but month 8 is actually September because:

  • 0 = January
  • 7 = August
  • 8 = September

Use 7 for August:

const date = new Date(2010, 7, 10);

2. Using getDay() instead of getDate()

getDay() does not return the day of the month. It returns the day of the week.

const date = new Date(2010, 7, 10);
console.log(date.getDay()); // weekday number, not 10

Use getDate() for the day number:

console.log(date.getDate()); // 10

3. Forgetting to add leading zeros

If you need a fixed-width date, 5-Aug-2010 may not be acceptable.

Broken version:

const day = date.getDate();

Better version:

const day = String(date.getDate()).padStart(2, "0");

4. Expecting direct string output in a custom format

This will not give 10-Aug-2010:

const date = new Date(2010, 7, 10);
console.log(date.toString());

toString() returns a full default representation, not a custom one.

5. Ignoring invalid dates

Broken example:

const date = new Date("not a real date");
console.log(date.getFullYear());

Safer approach:

if (isNaN(date)) {
  console.log("Invalid date");
}

6. Assuming locale formatting always matches your exact design

Intl.DateTimeFormat is powerful, but exact separators and order can vary. If your UI requires a precise format, manual formatting may be more reliable.

Comparisons

ApproachBest forProsCons
Manual formatting with getDate(), getMonth(), getFullYear()Exact custom formats like 10-Aug-2010Full control, simple, no library neededMore code to write
Intl.DateTimeFormatLocale-aware displayBuilt-in, readable, internationalization supportExact output may vary by locale
date.toString()DebuggingVery easyNot suitable for custom display
date.toISOString()APIs and machine-readable datesStandard format, great for backend communicationNot human-friendly for many UIs

Manual formatting vs Intl.DateTimeFormat

// Manual
function formatDate(date) {
  const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
  return `${String(date.getDate()).padStart(2, "0")}-${months[date.getMonth()]}-${date.getFullYear()}`;
}

// Intl
const formatter = new Intl.DateTimeFormat("en-GB", {
  day: "2-digit",
  month: "short",
  year: "numeric"
});

Choose:

  • manual formatting when you need exact output
  • Intl.DateTimeFormat when you want locale-aware user-facing dates
Take Quiz

Cheat Sheet

Quick reference

Create a date

const date = new Date(2010, 7, 10);
  • Year: 2010
  • Month: 7 means August
  • Day: 10

Important methods

date.getDate();      // day of month: 1-31
date.getMonth();     // month index: 0-11
date.getFullYear();  // 4-digit year
date.getDay();       // weekday index: 0-6

Month names

const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

Format as DD-MMM-YYYY

function formatDate(date) {
  const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
  const day = String(date.getDate()).padStart(2, "0");
  const month = months[date.getMonth()];
  const year = date.getFullYear();
  return `${day}-${month}-${year}`;
}

Example

console.log(formatDate(new Date(2010, 7, 10)));
// 10-Aug-2010

Common rules

  • Months are zero-based in the constructor and getMonth()
  • Use getDate() for the day of the month
  • Use padStart(2, "0") for leading zeros
  • Use manual formatting for exact custom strings
  • Use Intl.DateTimeFormat for locale-aware formatting

FAQ

How do I format a JavaScript date as 10-Aug-2010?

Create a Date, extract the day, month, and year, convert the month number to a short name, and join them into a string.

Why does JavaScript show the wrong month sometimes?

Because months are zero-based. January is 0, August is 7, and December is 11.

Should I use getDay() or getDate()?

Use getDate() for the day of the month. getDay() returns the weekday number.

Can I format dates without a library in JavaScript?

Yes. For simple formats, built-in Date methods are enough.

What is the easiest way to add a leading zero to the day?

Use:

String(date.getDate()).padStart(2, "0")

Is Intl.DateTimeFormat better than manual formatting?

It is better for locale-aware formatting, but manual formatting is often better when you need an exact layout like 10-Aug-2010.

What happens if the date is invalid?

Methods like getFullYear() may return invalid results. Check with isNaN(date) before formatting.

Can I reuse the same formatting logic in many places?

Yes. Put the logic in a helper function such as formatDate(date) and call it wherever needed.

Take Quiz

Mini Project

Description

Build a small date-formatting utility that takes JavaScript Date objects and prints them in DD-MMM-YYYY format. This demonstrates extracting date parts, handling zero-based months, adding leading zeros, and reusing formatting logic in a function.

Goal

Create a reusable formatDate() function that returns strings like 10-Aug-2010 and use it with multiple dates.

Requirements

["Create a function named formatDate that accepts one Date object","Return the date in DD-MMM-YYYY format","Add a leading zero when the day has only one digit","Use month abbreviations such as Jan, Feb, and Aug","Test the function with at least three different dates"]

Take Quiz

Keep learning

Related questions

View more