Loading...

How to convert string to date in JavaScript?

How to convert string to date in JavaScript?

When building an application, we often need to show a date to the user. For example, users would like to see when a blog article was posted. Dates are used everywhere, usually, a date is also stored with every entry on a database for keeping records. Even the article you are reading right now has a date associated with it! But dates can be painful to work with, especially with all the different formats and time zones. And if you are working with an API on the Front-end, dates are mostly returned as a string or as a timestamp from the API. So in this article, we will briefly look at the JavaScript Date object and the different ways of converting a string or a timestamp to a Date object. In the end, you will be comfortable in converting strings and timestamps to Date, and working with them.

The JavaScript Date object

Before we convert strings to Date, let us briefly discuss the Date object. The Date object in JavaScript is a built-in object that contains a lot of useful information about the specified date and time. It has a lot of useful properties and methods for working with dates and also formatting them.

We can create a Date object that holds the current time (Taken from the computer’s time) by simply calling new Date() without passing any arguments to its constructor. It should look something like this,

const currentTime = new Date(); // print the time console.log(currentTime.toString()); // Output //"Tue Nov 15 2022 13:12:38 GMT+0530 (India Standard Time)"
Code language: JavaScript (javascript)

If you notice the output, it is in the following format to be more human-readable: <Day of the week> <Month> <Day> <Year> <Hour>:<Minute>:<Second> <Timezone>

Now that we have our Date object, there are a bunch of cool methods we can use to manage and format it the way we want. For example, we can make it more user-friendly by using the toLocaleString() method. It should look like this,

console.log(currentTime.toLocaleString()); // "11/15/2022, 1:28:36 PM"
Code language: JavaScript (javascript)

It is a much better format to look at! There are so many methods in the Date object that it can be an article on its own, but this should be enough to get us up and running. If you want to learn more about the Date object, you can read the MDN docs about Date.

Convert string to Date

Now that we have briefly discussed working with dates in JavaScript, let us look at the problem at hand. In order to convert a string to Date, we first need to make sure the string is in the correct format. The Date object supports 2 kinds of date strings as arguments to its constructor. These are as follows,

  • “year-month-date”
  • “year/month/date”

For example, “2022/11/15” is accepted but “15/11/2022” will not be accepted. If your date string does not look like this, you should first manipulate your string so that it is in the correct format.

Once you have your string in the desired format, you can simply pass the string as an argument to the Date constructer. It is very similar to when we created a Date object before. Your code should look something like this,

var myDate = new Date("2022-11-15"); var anotherDate = new Date("2022/11/15"); // printing the dates console.log(myDate.toString()); console.log(anotherDate.toString()); // output //"Tue Nov 15 2022 05:30:00 GMT+0530 (India Standard Time)" //"Tue Nov 15 2022 00:00:00 GMT+0530 (India Standard Time)"
Code language: JavaScript (javascript)

How easy was that? As you can see above, we have used both the string formats mentioned earlier. Now we can use all the cool methods the Date object provides us with to manage and format the date as we please!

Convert timestamp to Date

A timestamp in milliseconds is basically the milliseconds passed since the UNIX epoch or January 1, 1970 00:00:00 UTC. It is also a popular way to store dates in databases as it is just a number. You can get the timestamp from a Date object by simply calling the getTime() method on it. Here’s an example using the current time,

console.log(new Date().getTime()); // output // 1668500997596
Code language: JavaScript (javascript)

Okay, we know what a timestamp is, but how do we convert it to a date object if we only have a timestamp?

First of all, if you have your timestamp as a string, you need to convert it to a JavaScript Number like so,

var ts = Number("1668500997596");
Code language: JavaScript (javascript)

If you already have the timestamp as a number, then you can ignore the step above.

Now we can simply pass the timestamp to the Date constructer as we did with the string formats. The code will look like this,

// optional if your have your ts as a number var ts = Number("1668500997596"); // convert to date var myDate = new Date(ts); // printing the date console.log(myDate.toString()); // "Tue Nov 15 2022 13:59:57 GMT+0530 (India Standard Time)"
Code language: JavaScript (javascript)

And we are done! We can now use all the methods in the Date object just from a timestamp, crazy how much info we can have just from a number right?

Just to prove the point about the epoch time, if you pass 0 as the timestamp you will get the epoch date as we mentioned earlier.

var myDate = new Date(0); console.log(myDate.toString()); // output // "Thu Jan 01 1970 05:30:00 GMT+0530 (India Standard Time)"
Code language: JavaScript (javascript)

Conclusion

Dates are used everywhere in computer programming just like in real life. Being able to effectively work with dates without using any external libraries is a useful skill to have. In this article, we briefly looked at the Date object in JavaScript, and how to create a Date object. We also learned how we can convert a valid date string and a timestamp into a Date object so that we can use all the useful methods the Date object provides. I hope this article has helped you clear your doubts about working with strings and dates. Now it is your time to use what you’ve learned in your own projects!

If you have any questions regarding this article or want to talk about anything technology, you can find me on Twitter. Thank you for reading!

Sharing is caring

Did you like what Supantha Paul wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far