How to Convert String to Date in Javascript

To convert string to date in JavaScript, use the date constructor or moment.js library. The Date() constructor creates a JavaScript Date instance that describes a single moment in time in a platform-independent format.

We already saw an example of how to convert date to string. Let’s see two approaches to converting string to date.

Using Date constructor

The Date() is a built-in JavaScript constructor that creates a Date instance that represents a single moment in time in a platform-independent format.

Syntax

new Date(string);

Parameters

string –  It takes a string as a YYYY/MM/DD format string. If we pass different formats that do not follow the ISO 8601 format, it will return an invalid date.

Example

const d = new Date("2022/4/18");

console.log(d)
console.log(d.getDate());
console.log(d.getFullYear());

Output

Mon Apr 18 2022 00:00:00 GMT+0530 (India Standard Time)
18
2022

In the above example, we convert a date string into a Javascript date. Then we can apply all methods to that date object.

In the example we use getDate() and getFullYear() method. And it’s a lot of methods that are very useful while we are working with data.

Using moment.js library

The moment.js library helps us parse, validate, manipulate, and display dates and times in JavaScript. It provides a moment() function which takes two arguments: stringDate and formatString.

Syntax

moment(stringDate, formatString)

Arguments

  1. stringDate:  We need to provide a string that we want to convert into a date.
  2. formatString:  You can provide the format of our string.

Installation

For HTML

If you are using simple HTML, you need to add these two script tags to your html file. After adding this scripts tag, you can easily use the moment.js.

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script type="module" src="index.js"></script>

For Framework, library

If you are using react, view, or any front-end library, you need to install it using npm.

npm i moment --save

Example

import moment from 'moment';

let string = "04-19-2022";
let dateObj = moment(string, "MM-DD-YYYY");

let stringvalue = dateObj.format("YYYY-MM-DD");
console.log(stringvalue);

Output

2022-04-19

In the above example, we pass a string and its format so it will return a date object.

In this dateObj, there are lots of methods we can use. But, first, we convert our mm-dd-yyyy format string into the yyyy-mm-dd format. 

If you are building a production-level project and there are many uses for this type of date conversion, you should use the moment library.

That’s it for converting string to date in JavaScript.

See also

How to Generate Dates Between Two Dates in JavaScript

Javascript Date Object

How to Convert Timestamp to Date in JavaScript

How to Convert Date to Timestamp in JavaScript

How to Add Days to Date in JavaScript

Leave a Comment