In this article, we will convert a string into a date using Javascript. A string can be converted into a date in JavaScript through the following ways.
Methods to Convert String to Date:
- Using JavaScript Date() constructor
- Using toDateString() method
- Using Date.parse() method
Method 1: Using JavaScript Date() constructor
Creating date object using date string: The date() constructor creates a date in human-understandable date form.
Example: In this example, we will convert a string into a date by creating a date object.
javascript
// It returns the Day,Month,Date,Year and time// Using Date() constructorlet d = new Date("May 1,2019 11:20:00");Â
// Display outputconsole.log(d); |
2019-05-01T11:20:00.000Z
Output:Â
Wed May 01 2019 11:20:00 GMT+0530 (India Standard Time)
Getting the string in DD-MM-YY format using suitable methods: We use certain methods such as:
- getDate-It Returns Day of the month(from 1-31)
- getMonth-It returns month number(from 0-11)
- getFullYear-It returns full year(in four digits )
Example: This example uses the approach to convert a string into a date.
Javascript
// Using Date() constructorlet d = new Date("May 1, 2019 ");Â
// Display outputconsole.log(formatDate(d));Â Â Â Â Â // Funciton to extract day, month, and year function formatDate(date) {Â Â Â Â let day = date.getDate();Â Â Â Â if (day < 10) {Â Â Â Â Â Â Â Â day = "0" + day;Â Â Â Â }Â Â Â Â let month = date.getMonth() + 1;Â Â Â Â if (month < 10) {Â Â Â Â Â Â Â Â month = "0" + month;Â Â Â Â }Â Â Â Â let year = date.getFullYear();Â Â Â Â return day + "/" + month + "/" + year;} |
01/05/2019
Method 2: Using JavaScript toDateString() method
This method returns the date portion of the Date object in human-readable form.Â
Example: This example shows the above-explained approach.
javascript
// Date objectlet date = new Date(2019, 5, 3);Â
//Display outputconsole.log(date.toDateString()); |
Mon Jun 03 2019
Method 3: Using Date.parse() method
The JavaScript Date parse() Method is used to know the exact number of milliseconds that have passed since midnight, January 1, 1970, till the date we provide.
Syntax:Â
Date.parse(datestring);
Example: In this example, we will use date.parse() method to get time out of the string and convert it to get date output.
Javascript
// Input string let d = "May 1, 2019 "Â
// Using Date.parse methodlet parse = Date.parse(d);Â
// Converting to date objectlet date = new Date(parse);Â
// Display outputconsole.log(date); |
Supported Browsers:
- Google Chrome
- Firefox
- Edge
- Opera
- Apple Safari
