In this article, we will convert a string into a date using JavaScript. A string must follow the pattern so that it can be converted into a date.
A string can be converted into a date in JavaScript through the following ways:
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
let d = new Date("May 1,2019 11:20:00");
console.log(d);
|
Output
2019-05-01T11:20:00.000Z
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
let d = new Date("May 1, 2019 ");
console.log(formatDate(d));
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;
}
|
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
let date = new Date(2019, 5, 3);
console.log(date.toDateString());
|
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
let d = "May 1, 2019 "
let parse = Date.parse(d);
let date = new Date(parse);
console.log(date);
|
Output
2019-05-01T00:00:00.000Z
Supported Browsers
- Google Chrome
- Firefox
- Edge
- Opera
- Apple Safari
Learn to code easily with our course
Coding for Everyone. This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
13 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...