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
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:
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.