I'm having trouble creating a js date variable from a c# datetime. I'm noticing some strange behaviour with jquerys .val() method.
An input element holds the date info, like this:
@Html.HiddenFor(t => t.Tasks[i].Task.Deadline, new { @class = "task-end", @Value = Model.Tasks[i].Task.Deadline.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds })
In the javascript, I'm doing this:
var date = new Date($("MyDateFromHiddenField").val());
Writing this date to the console gives invalid date.
If I write $("MyDateFromHiddenField").val() to the console I get 1372854195130
Hardcoding the date with this number will give me a valid date:
var date = new Date(1372854195130); <---Valid
For some reason, new Date() doesn't like the .val() method.
Example: http://jsfiddle.net/hZ7bm/1/
The issue is that .val() returns a string and new Date() expects a number. You can update your call to:
var date = new Date(parseInt($("#myhidden").val(), 10));
An updated version is at http://jsfiddle.net/hZ7bm/2/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With