Date object, which primarily represents the current date and time in the timestamp format. The
Date object also allows you to initialize a specific date, which is in one of the standard formats. Once you instantiate a
Date object, it provides several utility methods that allow you to get various components of the date and time, and you can use these various methods to format a date in different ways.
However, when it comes to changing a date from one format to another, there’s no straightforward way to convert a date to your desired format. In this article, I'll show you how to build a utility function, which allows you to convert a date from one format to another. At the end, we’ll also discuss a popular third-party library that allows you to change a date into different formats.
Let’s have a quick look at the following example.
As you can see, we’ve implemented the
dateFormat function, which takes two arguments. The first argument is the source date, and the second argument is the desired date format to which the source date will be converted. It’s important to note that the second argument must be a valid date format containing
Now, let's go through the
dateFormat function. Firstly, we’ve instantiated the
Date object by passing the source date as the first argument of the constructor.
Next, we’ve used the
getYear() methods of the
Date object to get the date components. It’s important to note that the month value starts with zero, so we have to increment the value by one to get the actual month. We’ve also used the
padStart method to format the month value with a leading zero if it’s needed. We do something similar with the year and day values.
With everything in place, you should be able to convert a date to your desired format.
Popular Date Manipulation Libraries
Let’s have a quick look at the Moment.js example to understand how it works.
As you can see, it’s fairly easy to convert a date into different formats with the use of this third-party library.