One of the most common tasks when working with dates is formatting them. In this blog post, we will learn how to convert a date from the format “YYYY-MM-DD” to “DD-MM-YYYY” in JavaScript.
Let’s say we have the following date string in the “YYYY-MM-DD” format:
const dateString = "2021-07-27";
Now, we will convert this date string to “DD-MM-YYYY” format using JavaScript. To achieve this, we can follow these steps:
- Split the date string into an array by using the split() method.
- Reverse the array elements.
- Join the reversed array elements back into a string using the join() method.
Here’s the JavaScript code that demonstrates how to do this:
function convertDateFormat(dateString) { const dateArray = dateString.split("-"); const reversedArray = dateArray.reverse(); const newDateString = reversedArray.join("-"); return newDateString; } const dateString = "2021-07-27"; const newFormatDate = convertDateFormat(dateString); console.log(newFormatDate); // Output: "27-07-2021"
Now, let’s explain the code:
- We defined a function named convertDateFormat() that takes a date string as its argument.
- Inside the function, we used the split() method to break the input date string into an array of substrings (year, month, and day).
- We then reversed the order of the array elements using the reverse() method.
- Finally, we joined the reversed array elements back into a string using the join() method and returned the resulting string.
So, by using this simple JavaScript function, we can easily convert a date string from “YYYY-MM-DD” format to “DD-MM-YYYY” format.