How To Convert String To Date In Javascript

Converting a string to a date is a common task in JavaScript when working with date and time data. In this blog post, we will learn how to convert a string to a date in JavaScript using the Date object and its built-in methods.

Using the Date Constructor

The simplest way to convert a string to a date in JavaScript is to use the Date constructor. The Date object accepts a string in a format that can be parsed by the Date.parse() method, and it returns a new date instance based on the provided string.

Here’s an example of how to use the Date constructor:

const dateStr = "2021-10-13T19:30:00";
const dateObj = new Date(dateStr);
console.log(dateObj);
// Output: Wed Oct 13 2021 19:30:00 GMT+0000 (Coordinated Universal Time)
    

Keep in mind that the string format must be understandable by the Date.parse() method, which supports the simplified ECMAScript ISO 8601 Extended Format.

Using the Date.parse() Method

Another way to convert a string to a date in JavaScript is to use the Date.parse() method. This method accepts a string in the same format as the Date constructor and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC (Unix Epoch).

Here’s an example of how to use the Date.parse() method:

const dateStr = "2021-10-13T19:30:00";
const timestamp = Date.parse(dateStr);
console.log(timestamp);
// Output: 1634155800000

const dateObj = new Date(timestamp);
console.log(dateObj);
// Output: Wed Oct 13 2021 19:30:00 GMT+0000 (Coordinated Universal Time)
    

Using Moment.js Library

If you need more advanced date and time manipulation, you can use the Moment.js library. This library provides more robust support for parsing and formatting dates, including strings in various formats.

Here’s an example of how to use Moment.js to convert a string to a date:

const moment = require("moment");

const dateStr = "13-10-2021 19:30";
const format = "DD-MM-YYYY HH:mm";
const dateObj = moment(dateStr, format);

console.log(dateObj.toDate());
// Output: Wed Oct 13 2021 19:30:00 GMT+0000 (Coordinated Universal Time)
    

Remember to install the Moment.js library before using it in your project:

npm install moment
    

Conclusion

In this blog post, we learned how to convert a string to a date in JavaScript using the Date constructor, the Date.parse() method, and the Moment.js library. These techniques can help you efficiently work with date and time data in your JavaScript projects.