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'));
Use the
new Date()
SyntaxYou 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), andDD
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:
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.
need an explanation for this answer? contact us directly to get an explanation for this answer