Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript date from c# DateTime [duplicate]

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/

like image 777
BlazeMan Avatar asked Jul 13 '26 15:07

BlazeMan


1 Answers

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/

like image 116
detaylor Avatar answered Jul 15 '26 05:07

detaylor