0

I'm passing a list of c# objects to my view via my viewmodel. The object has a 'EndDate' (DateTime type) as a property. Then I encode it to a Json object array to be used in Javascript. In Javascript I try to read the 'EndDate' property and then set it to a input field of type DateTime but the value is some long string that I don't recognize. How do I convert this back or use it?

Here is my code.

In my view I set the list of objects to a js variable

<script type="text/javascript">
    var availableLicenses =  @Html.Raw(Json.Encode(Model.AvailableLicenses));
</script>

When I look at the EndDate property in Chrome dev tools it looks like this. enter image description here enter code here

I want to set this EndDate value "/Date(1501459200000)/" to a date value for a DateTime input element, but I'm not sure how to convert it?

<input id="EndDate"type="datetime" value="put converted date here" required>
chuckd
  • 13,460
  • 29
  • 152
  • 331
  • 1
    Possible duplicate of [ASP.NET MVC JsonResult Date Format](http://stackoverflow.com/questions/726334/asp-net-mvc-jsonresult-date-format) –  Aug 08 '16 at 12:48

2 Answers2

0
value = new Date(parseInt(value.replace("/Date(", "").replace(")/",""), 10));

This is answered by ASP.NET MVC JsonResult Date Format

Community
  • 1
  • 1
0

The number inside parentheses is an epoch date (milliseconds since 1/1/1970). The conversion to date is simple. The logic is straightforward: remove all non-digits (\D) and convert to Date().

availableLicenses.EndDate = new Date(parseInt(availableLicenses.EndDate.replace(/\D/g,'')));
console.log(availableLicenses.EndDate); 
// Date {Sun Jul 30 2017 19:00:00 GMT-0500 (Central Standard Time)}
//note: timezone will be yours.
Alex Kudryashev
  • 9,120
  • 3
  • 27
  • 36