How to Format a Date in JavaScript?

How to Format a Date in JavaScript?

Problem Statement

JavaScript applications often need formatted dates. While JavaScript’s Date object provides utilities, it doesn’t directly offer a variety of formatted outputs like MM/DD/YYYY or YYYY-MM-DD. This guide explains how to achieve different date formats.


Solution Code

Here’s a quick reference of various date formats with corresponding methods:

Format Description Code Example Output Example
MM/DD/YYYY U.S. date format date.toLocaleDateString("en-US", { year: "numeric", month: "2-digit", day: "2-digit" }) 11/13/2024
DD-MM-YYYY European date format `${String(date.getDate()).padStart(2, '0')}-${String(date.getMonth() + 1).padStart(2, '0')}-${date.getFullYear()}` 13-11-2024
YYYY-MM-DD ISO format date.toISOString().split('T')[0] 2024-11-13
Full Date Human-readable format date.toDateString() Wed Nov 13 2024
Time Only Time in HH:MM:SS date.toTimeString().split(' ')[0] 18:25:43
Custom Format Full custom date-time format `${String(date.getDate()).padStart(2, '0')}-${String(date.getMonth() + 1).padStart(2, '0')}-${date.getFullYear()} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}` 13-11-2024 18:25

Learn More

Let’s dive deeper into the methods:

  1. Locale Formatting with toLocaleDateString()

    • Format: MM/DD/YYYY
    • Description: Quickly formats dates based on the locale, offering options for customization.

    Example:

const date = new Date();

const formattedDate = date.toLocaleDateString("en-US", {
  year: "numeric",
  month: "2-digit",
  day: "2-digit",
});

console.log(formattedDate); // Output: "12/03/2024" (MM/DD/YYYY format)

  1. Custom Formatting with String Manipulation

    • Format: DD-MM-YYYY
    • Description: Provides precise control over format using string manipulation and methods like padStart().

    Example:

   const date = new Date();
   const day = String(date.getDate()).padStart(2, '0');
   const month = String(date.getMonth() \+ 1).padStart(2, '0');
   const year = date.getFullYear();
   const customDate = \`${day}-${month}-${year}\`;
   console.log(customDate); // Output: "13-11-2024"

  1. ISO Format with toISOString()

    • Format: YYYY-MM-DD
    • Description: Outputs a standardized ISO 8601 format, great for databases and backends.

    Example:

   const date = new Date();
   console.log(date.toISOString().split('T')\[0\]); // Output: "2024-11-13"

  1. Readable Formats with toDateString()

    • Format: Wed Nov 13 2024
    • Description: Outputs a simple, human-readable format.

    Example:

   const date = new Date();
   console.log(date.toDateString()); // Output: "Wed Nov 13 2024"

  1. Extracting Time Only with toTimeString()

    • Format: HH:MM:SS
    • Description: Retrieves the time portion from a date.

    Example:

   const date = new Date();
   console.log(date.toTimeString().split(' ')\[0\]); // Output: "18:25:43"

  1. Complex Custom Formats

    • Format: DD-MM-YYYY HH:MM
    • Description: Combines date and time components for full customization.

    Example:

const date = new Date();
const day = String(date.getDate()).padStart(2, '0');
const month = String(date.getMonth() + 1).padStart(2, '0');
const year = date.getFullYear();
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const customDateTime = `${day}-${month}-${year} ${hours}:${minutes}`;
console.log(customDateTime); // Output: "13-11-2024 18:25"

Summary

  • toLocaleDateString(): Best for localized formats (MM/DD/YYYY, DD/MM/YYYY, etc.).
  • toISOString(): Ideal for standardized storage or transmission.
  • String Manipulation: Use when precise, custom formats are needed.
  • Libraries: Consider date-fns or Day.js for advanced formatting or better time zone support.

References


Quick Recap of Date Formatting in JavaScript: Techniques for toLocaleDateString(), Custom Strings, and More

Thank you so much for reading "How to Format a Date in JavaScript"! We’re thrilled that you found the content helpful and insightful in learning how to format dates effectively using JavaScript. In this article, we explored various date formatting techniques, from using JavaScript's built-in Date object methods like toLocaleDateString() and toISOString(), to manipulating dates with string techniques. These methods provide you with the flexibility to format dates in any style you need—whether that's a simple MM/DD/YYYY or a more custom format tailored to your project.

To help you master date formatting in JavaScript, here are some exciting topics you can dive into next:

  1. Internationalization and Localization of Dates – Learn how to format dates for different regions and languages using toLocaleDateString() and Intl.DateTimeFormat.
  2. Using formatToParts() for Custom Date Formatting – Discover how to break down a date into parts (day, month, year) and manipulate them for highly customizable formats.
  3. Timezone Considerations in Date Formatting – Explore how JavaScript handles time zones, and how powerful libraries like Luxon can assist with complex time zone formatting.
  4. ISO 8601 Format and Usage – Understand why ISO 8601 is the go-to date format for APIs, databases, and global interoperability.
  5. String Manipulation for Custom Date Formatting – Master advanced string manipulation techniques to create complex custom date formats.
  6. Date Libraries and JavaScript Date Handling – Compare JavaScript Date object methods with popular libraries like Moment.js and date-fns for more advanced date manipulation.
  7. Performance Considerations – Get insights into the performance of date formatting methods, especially when handling large datasets or frequent date operations.
  8. Legacy Browser Compatibility – Learn how to handle date formatting issues in older browsers using polyfills and other workarounds.

We hope this article inspires you to keep exploring the exciting world of JavaScript and date handling. Dive into the topics shared above, experiment with code, and challenge yourself to create better, more dynamic applications. The possibilities with JavaScript are endless—so keep coding, keep growing, and happy learning!


Compiled by team Crio.Do

You've successfully subscribed to Crio Blog
Great! Next, complete checkout to get full access to all premium content.
Welcome back! You've successfully signed in.
Unable to sign you in. Please try again.
Success! Your account is fully activated, you now have access to all content.
Error! Stripe checkout failed.
Success! Your billing info is updated.
Billing info update failed.