How can I pass a string date from a variable to the new Date(...)
constructor? The following code produces Invalid Date
. Do I need to convert it first somehow?
var dateString = '18/11/2021';
var dateObject = new Date(dateString);
alert(dateObject);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
When using the Date(dateString)
constructor, the date string must be specified in simplified ISO 8601 date format. Also note that conforming date only formats such as yyyy-mm-dd
are treated as UTC, not local. The following should produce the expected result:
alert(new Date("2021-11-18T00:00:00"));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Using any non-standard format is discouraged and the results are implementation specific.
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>