Getting date formats right in JavaScript can be a challenge — especially when there are many different input and output formats. There are some JavaScript packages that can help with this task but it might be hard to justify the package size for a simple date string. Sometimes it is better to keep things simple so in this blog you will learn how to format a date as DD/MM/YYYY using pure JavaScript.
JavaScript dates use the ISO standard by default. This means that if you simply want a string for a date using native JavaScript methods, you will be faced with a couple different options that are meant to keep things as standardized as possible.
These are all great at what they do but what if you specifically need the DD/MM/YYYY format? Using toLocaleDateString()
is close but its format varies based on the browser’s time zone and language.
You could use the ISO version of the date string provided by toISOString()
to perform a few string operations to move around the dates. This is a potentially usable solution but perhaps not the most clear or concise. There must be something better.
The most straightforward way to create a date string in DD/MM/YYYY format involves using a few native get()
methods and some simple logic. The first step is to get the date’s month, date, and year. Be careful here — JavaScript months are 0 based so you’ll need to increment the month by one.
Once you have these values you can add 0’s to the month and date where necessary:
If you prefer a newer ES2017 approach, you can refactor the logic above by utilizing the padStart()
method. This is a native string method first introduced with ES2017 that accepts the desired length as the first parameter and the string to fill with as the second parameter. In this case, you want the value of the month or date to always be exactly two digits long so that will be the first parameter. The value should either start with 0 or naturally be two digits long so 0 will be the second parameter as follows:
Put these values together and you’ll have your date formatted as a DD/MM/YYYY string:
That’s it! One great thing about this solution is that since you have all three parts of the date broken up, you can easily use this logic to create any desired date string format. Using dates can be tricky in general and JavaScript’s native solutions are not exactly intuitive for every use case. Fortunately, it is simple enough to get the date format you want with only a few lines of code.
Here is the full solution:
For those of you who enjoy finding fun one-liners to use in their code, there is actually a more elegant solution to formatting a date as DD/MM/YYYY. Remember the toLocaleDateString()
method mentioned earlier? It accepts a locale string as a parameter. If you use the British English locale of 'en-GB'
you’ll get the format you wanted in just one line of code.
wow