How To Parse Date In Dd-Mm-Yyyy Format In Javascript

Working with dates can be tricky, especially when dealing with different date formats. In this blog post, we will discuss how to parse a date in the DD-MM-YYYY format using JavaScript. This format is commonly used in many countries, and being able to handle it correctly is essential for any application dealing with dates.

Using the Date.parse() Method

JavaScript provides a built-in method called Date.parse() that can be used to parse a date string. However, this method doesn’t work well with the DD-MM-YYYY format, as it expects the date string to be in the format MM-DD-YYYY. Therefore, we will need to write a custom function to handle the DD-MM-YYYY format correctly.

Creating a Custom Function

Let’s create a custom function called parseDate() that takes a date string in the DD-MM-YYYY format and returns a JavaScript Date object. This function will first extract the day, month, and year values from the input string and then create a new Date object using these values. Here’s the code:

function parseDate(dateString) {
    const [day, month, year] = dateString.split('-');
    return new Date(year, month - 1, day);
}

Let’s break down this function step by step:

  1. We use the split() method to break the input date string into an array of strings, using the ‘-‘ character as the separator.
  2. We then use destructuring assignment to extract the individual day, month, and year values from the resulting array.
  3. Finally, we create a new Date object using the new Date() constructor, passing the year, month (subtracting 1, as JavaScript months are 0-based), and day values.

Using the parseDate() Function

Now that we have our custom parseDate() function, we can use it to parse a date string in the DD-MM-YYYY format. Here’s an example:

const dateString = '31-12-2021';
const dateObject = parseDate(dateString);
console.log(dateObject);

This code will output the following Date object:

2021-12-31T00:00:00.000Z

Conclusion

In this blog post, we have discussed how to parse a date in the DD-MM-YYYY format using JavaScript. By creating a custom function called parseDate(), we can easily handle dates in this format, which is commonly used in many countries. This function can be a valuable addition to any application that needs to deal with dates in different formats.