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.
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 monthgetMonth()returns a month index from0to11getFullYear()returns the 4-digit year- the
monthsarray converts month numbers into names likeAug
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:
-
new Date(2010, 7, 10)creates a date.- Year =
2010 - Month =
7 - Day =
10
- Year =
-
The month is
7, but JavaScript months are zero-based:0= January7= August
-
date.getDate()returns10. -
String(...).padStart(2, "0")turns10into a 2-character string.10stays10- if it were
5, it would become05
-
date.getMonth()returns7. -
months[7]gives"Aug". -
date.getFullYear()returns2010. -
Template literals combine the pieces:
10Aug2010
-
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
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= January7= August8= 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
| Approach | Best for | Pros | Cons |
|---|---|---|---|
Manual formatting with getDate(), getMonth(), getFullYear() | Exact custom formats like 10-Aug-2010 | Full control, simple, no library needed | More code to write |
Intl.DateTimeFormat | Locale-aware display | Built-in, readable, internationalization support | Exact output may vary by locale |
date.toString() | Debugging | Very easy | Not suitable for custom display |
date.toISOString() | APIs and machine-readable dates | Standard format, great for backend communication | Not 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.DateTimeFormatwhen you want locale-aware user-facing dates
Cheat Sheet
Quick reference
Create a date
const date = new Date(2010, 7, 10);
- Year:
2010 - Month:
7means 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.DateTimeFormatfor 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.
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"]
Keep learning
Related questions
Abort Ajax Requests with jQuery jqXHR.abort()
Learn how to cancel an in-progress jQuery Ajax request with jqXHR.abort(), handle abort status safely, and avoid stale UI updates.
Access the Correct this Inside a JavaScript Callback
Learn why JavaScript this changes in callbacks and how to preserve an object context using bind, arrow functions, and event handler patterns.
Add Key-Value Pairs to JavaScript Objects
Learn how to add key-value pairs to JavaScript objects with dot and bracket notation, dynamic keys, examples, and common mistakes.