0

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);
Salman A
  • 248,760
  • 80
  • 417
  • 510
sonicfroots
  • 111
  • 1
  • Does this answer your question? [Format date to MM/dd/yyyy in JavaScript](https://stackoverflow.com/questions/11591854/format-date-to-mm-dd-yyyy-in-javascript) – Bijan Nov 04 '21 at 15:58

2 Answers2

2

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"));

Using any non-standard format is discouraged and the results are implementation specific.

Salman A
  • 248,760
  • 80
  • 417
  • 510
0

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

hello = '2021/11/18';
end = new Date(hello);
alert(end);
Maik Lowrey
  • 10,972
  • 4
  • 14
  • 43