In this tutorial, we are going to format the Date variable into “dd/mm/yyyy” using these built-in methods:
- getFullYear(): Returns as the full year in four-digit format
- getMonth(): Returns the month from a Date variable, remember that the month starts from 0 for January, so you need to add 1 to avoid confusion
- getDate(): Returns us the date of the month from a Date variable
Creating a new Date Variable in Javascript
To start, we first need a date for that we are simply going to use the Date object to get the current date, and we are going to store that inside a variable “currentDate”. For this, use the following line:
Now, we can get the current format of this newly created Date variable by using console log:
This is not the format, so we are going to work on this now step by step.
Getting month in the correct “mm” format
Let’s first get the month from this date by using the getMonth() function as
We have added 1 to our month because the month in the date variable starts from 0. After that, we need to make sure that the month is not in single-digit, so we induce the following check on it:
This would change the single-digit month into two digits, or we can in the format “mm”.
Getting Date in the correct “dd” format
We are going to fetch the date of the month using the getDate() function:
Then we check for a single-digit date and convert it into two digits using the following line:
Now we have our date into the correct format as well.
Getting year in the correct “yyyy” format
Finally, we get our year from the Date variable using the getFullYear() method as
getFullYear() returns the year in the “yyyy” format. Therefore, we don’t need to put a check on it.
Compiling the complete Date in the correct format
Finally, we need to put all these 3 components of our “date” together into a new variable using the following line of code:
At the end, use the console log function to print out the “formattedDate” onto the console as:
The complete code snippet is as follows:
console.log(currentDate);
var month = currentDate.getMonth();
if (month < 10) month = "0" + month;
var dateOfMonth = currentDate.getDate();
if (dateOfMonth < 10) dateOfMonth = "0" + dateOfMonth;
var year = currentDate.getFullYear();
var formattedDate = dateOfMonth + "/" + month + "/" + year;
console.log(formattedDate);
Upon execution you will get the following output on your screen:
Conclusion
Converting a date variable into a specific format may seem very daunting at first. But date formatting can very easily be achieved by using the built-in function that comes with ES6 JavaScript. In this tutorial post, we learned how to format a date in dd/mm/yyyy format using the three basic functions: getMonth (), getDate and getFullYear().