How To Parse Date In Javascript

Working with dates is a common task for web developers, and JavaScript provides several ways to parse, format, and manipulate date objects. In this blog post, we’ll learn how to parse a date string into a JavaScript Date object and then format the output to display it in a readable way.

Creating a Date Object

The first step in parsing a date in JavaScript is to create a new Date object. You can create a new date object using the new Date() constructor. There are several ways to create a new date object, but for this tutorial, we’ll focus on creating a date object from a date string.

To create a date object from a date string, simply pass the date string as a parameter to the new Date() constructor. Here’s an example:

const dateString = "2022-02-20";
const dateObj = new Date(dateString);
console.log(dateObj);

In this example, we’ve created a new date object from the date string “2022-02-20”. The console.log will output the date in the default format, which usually looks like this: Sun Feb 20 2022 00:00:00 GMT+0000 (Coordinated Universal Time).

Formatting the Date Output

Now that we have a date object, we can format the output to display the date in a more human-readable way. We can do this by using the various methods available on the Date object.

For example, let’s say we want to display the date in the format MM/DD/YYYY. We can do this using the getMonth(), getDate(), and getFullYear() methods:

const month = dateObj.getMonth() + 1; // getMonth() returns 0-11, so we need to add 1
const day = dateObj.getDate();
const year = dateObj.getFullYear();

const formattedDate = `${month}/${day}/${year}`;
console.log(formattedDate); // Output: 2/20/2022

In this example, we’re using template literals to build the formatted date string by inserting the values of month, day, and year variables.

Conclusion

In this blog post, we’ve learned how to parse a date string into a JavaScript Date object and format the output to display it in a readable way. We’ve covered creating a date object using the new Date() constructor and formatting the output using various Date object methods.

Keep in mind that there are many other ways to manipulate and format dates in JavaScript. If you want more advanced date formatting and manipulation features, you can also consider using a library like Moment.js or date-fns.