2

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/

tereško
  • 58,060
  • 25
  • 98
  • 150
BlazeMan
  • 147
  • 3
  • 11

5 Answers5

3

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/

detaylor
  • 7,112
  • 1
  • 27
  • 46
2

Use parseInt instead of passing the string returned by .val to the Date constructor.

var date = new Date(parseInt($("MyDateFromHiddenField").val(), 10));

As a string it will be invalid:

new Date("1372854195130")
// Invalid Date
Matt Zeunert
  • 16,075
  • 6
  • 52
  • 78
2

The parameter to the Date constructor should be a number instead of string. Try parseInt as suggested by others, or could try:

var date = new Date(+$("#myhidden").val());

+ will convert string to number

DEMO

Khanh TO
  • 48,509
  • 13
  • 99
  • 115
2

values from the input fields are in string data type. So you have to convert it to integer using parseInt(string, radix) or Number(string)

var date = new Date(parseInt($("#myhidden").val(), 10));

or

var date = new Date(Number($("#myhidden").val()));
Praveen
  • 55,303
  • 33
  • 133
  • 164
0

Try this:

 var date = new Date(parseInt(1372854195130, 10));
  var curr_month = ('0' + (date.getMonth() + 1));
  var curr_date = ('0' + (date.getDate()));
  var curr_year = date.getFullYear();
Saritha.S.R
  • 800
  • 1
  • 6
  • 19