convert date to string format dd/mm/yyyy javascript

Convert Date to String Format dd/mm/yyyy in JavaScript

If you are working with dates in JavaScript, you might need to convert them to a string format that is easy to read and understand. In this tutorial, we will show you how to convert a date object to a string format "dd/mm/yyyy" using JavaScript.

Method 1: Using the toLocaleDateString() Method

The easiest way to convert a date object to a string format "dd/mm/yyyy" is by using the toLocaleDateString() method. This method returns a string with a language-sensitive representation of the date.


      const date = new Date();
      const dateString = date.toLocaleDateString("en-GB");
      console.log(dateString); //output: "dd/mm/yyyy"
    

In the example above, we created a new Date object and called the toLocaleDateString() method on it. The "en-GB" parameter specifies the locale for the date string, which in this case is British English. The method returns a string in the format "dd/mm/yyyy", which we stored in the dateString variable and logged to the console.

Method 2: Using the formatDate() Function

If you want more control over the date format, you can create your own function to format the date string. Here is an example of a function that formats a date object to "dd/mm/yyyy" format:


      function formatDate(date) {
        const day = date.getDate().toString().padStart(2, "0");
        const month = (date.getMonth() + 1).toString().padStart(2, "0");
        const year = date.getFullYear().toString();
        return `${day}/${month}/${year}`;
      }
      const date = new Date();
      const dateString = formatDate(date);
      console.log(dateString); //output: "dd/mm/yyyy"
    

In the example above, we defined a function called formatDate() that takes a Date object as a parameter. The function extracts the day, month, and year components of the date using the getDate(), getMonth(), and getFullYear() methods, respectively. We then use the padStart() method to add leading zeros to the day and month components if they are less than 10. Finally, we return a string that concatenates the day, month, and year components in "dd/mm/yyyy" format.

We then created a new Date object and called the formatDate() function on it. The function returns a string in the desired format, which we stored in the dateString variable and logged to the console.

These are two simple ways to convert a date object to a string format "dd/mm/yyyy" in JavaScript. You can choose the method that works best for your use case.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe