Home > Net >  Pass a string variable into new Date() constructor
Pass a string variable into new Date() constructor

Time:11-05

How can I pass a string date from a variable into the new Date constructor? See code below. Do I need to convert it first somehow? The alert comes back as invalid. Thanks.

var hello = '18/11/2021';
var end = new Date(hello);
alert(end);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

When using one argument, string constructor, the date must be specified in simplified ISO 8601 date format. yyyy-mm-dd works just fine. Using any other format not described in the linked reference is discouraged and the results are implementation specific.

hello = '2021-11-18';
end = new Date(hello);
alert(end);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

it's your dateString format. First the year, month and then day.

hello = '2021/11/18';
end = new Date(hello);
alert(end);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related