JavaScript Date Formats
8 April 2025 | Category: JavaScript
JavaScript can handle multiple date formats when creating a Date
object. However, not all formats are reliable across browsers.
Understanding date formats helps you parse and display dates correctly in your apps.
â 1. ISO 8601 (International Standard)
đ Recommended Format â Accurate and cross-browser compatible.
const date1 = new Date("2025-04-08");
console.log(date1); // Tue Apr 08 2025
With time and time zone:
const date2 = new Date("2025-04-08T10:30:00Z");
console.log(date2); // UTC time
â Always use this format for APIs and database communication.
â 2. Short Date Format
const date3 = new Date("04/08/2025"); // MM/DD/YYYY
console.log(date3); // Tue Apr 08 2025
â ď¸ Not recommended internationally â can be confused with DD/MM/YYYY in other countries.
â 3. Long Date Format
const date4 = new Date("April 8, 2025");
console.log(date4); // Tue Apr 08 2025
You can also include the day of the week:
const date5 = new Date("Tue Apr 08 2025");
â ď¸ This format depends on the browser’s ability to parse strings.
â 4. Specifying Date Parts
You can also create a date using numeric parts:
const date6 = new Date(2025, 3, 8); // Month is 0-based (0 = Jan)
console.log(date6); // Tue Apr 08 2025
â Invalid or Unsupported Formats
const badDate = new Date("08-04-2025");
console.log(badDate); // Invalid Date (in some browsers)
â ď¸ Avoid ambiguous formats like
DD-MM-YYYY
.
đ§ How JavaScript Reads Dates
Format Type | Example | Notes |
---|---|---|
ISO (recommended) | "2025-04-08" | Safe and accurate |
Short date | "04/08/2025" | U.S. format (MM/DD/YYYY) |
Long date | "April 8, 2025" | Browser-dependent |
Date parts | new Date(2025, 3, 8) | Reliable, month is 0-based |
đ§Ş Checking Valid Dates
Always check if a date is valid:
const date = new Date("invalid-date");
if (isNaN(date.getTime())) {
console.log("Invalid date");
} else {
console.log("Valid date");
}
đ Converting to Different Formats
Use built-in methods to output formatted strings:
const today = new Date();
today.toDateString(); // "Tue Apr 08 2025"
today.toISOString(); // "2025-04-08T10:30:00.000Z"
today.toLocaleDateString(); // Depends on user locale
You can customize toLocaleDateString()
:
today.toLocaleDateString("en-GB"); // "08/04/2025"
today.toLocaleDateString("en-US"); // "4/8/2025"
đ Final Notes
- Use ISO format whenever possible.
- Be careful with ambiguous formats across regions.
- Always validate date inputs for safety and consistency.