WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES

How to Parse a String to a Date Object in JavaScript

Topic: JavaScript / jQueryPrev|Next

Answer: Use the new Date() Syntax

You can simply use the Date() constructor to parse or convert a string to a Date object in JavaScript.

However, your date string should be in proper format that's accepted worldwide, e.g., YYYY-MM-DD. Here, YYYY represents the 4-digit year, MM represents 2-digit month (where January is 01 and December is 12), and DD represents 2-digit date of the month (0 to 31).

Let's take a look at the following example to understand how it basically works:

// Sample date string
var str = '2021-10-08';

// Ceating the date object
var date = new Date(str);
console.log(date);

You can skip the DD or MM parts. When the DD or MM elements are absent, "01" will be used.

The following example shows what happen when you skip the DD or MM parts.

// Omit the DD part
console.log(new Date('2021-10'));

// Omit both MM and DD parts
console.log(new Date('2021'));

Related FAQ

Here are some more FAQ related to this topic:

Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties