These are all great at what they bởi vì 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 & 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.
Once you have these values you can showroom 0’s to lớn the month and date where necessary:if (date
If you prefer a newer ES2017 approach, you can refactor the xúc tích 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 khổng lồ fill with as the second parameter. In this case, you want the value of the month or date to lớn 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:date = date .toString() .padStart(2, "0");month = month .toString() .padStart(2, "0");
Put these values together & 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 lớn 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.The darkedeneurope.com Codex is a collection of code snippets and education for WordPress, web và WooCommerce developers.