Search code examples
javascriptc#.net-corerazor-pages

Invalid date on JavaScript on .Net Core project


I'm having the next issue:

<input type="hidden" value="@Model.EndDate" id="dateEnd" />

in the hidden input, I have a Date value from a Model this value is 2019/12/31

So I'm trying to use it in JavaScript for some logic in the webpage, here is how I catch it:

const endDate = new Date(document.querySelector("#dateEnd").value);

When I do this and do a "console.log", the console shows me "Invalid Date".

Any idea why this happens?


Solution

  • You are rendering the value of a .NET DateTime to the hidden field without any formatting. The output will be 31/12/2019 00:00:00, not the 31/12/2019 that you posted. You can check this by using the browser developer tools. JavaScript is unable to convert that value to a date.

    Ideally, when working with dates in HTML, you should use an ISO 8601 format to prevent this kind of issue. You can use a DateTime format string to do this:

    <input type="hidden" value="@Model.EndDate.ToString("yyyy-MM-dd")" id="dateEnd" />