I have a date as a string:
var mydate = "05/05/2011"
when I pass this var to a function like:
myfunction(mydate);
I alert the results and get a decimal not the string date:
function myfunction(mydate){
alert(mydate);
}
produces :
0.0004972650422675286
how do I get it back to a date?
I have a date as a string:
var mydate = "05/05/2011"
when I pass this var to a function like:
myfunction(mydate);
I alert the results and get a decimal not the string date:
function myfunction(mydate){
alert(mydate);
}
produces :
0.0004972650422675286
how do I get it back to a date?
Share Improve this question edited Apr 22, 2011 at 18:13 John Giotta 17k7 gold badges54 silver badges83 bronze badges asked Apr 22, 2011 at 18:10 BarclayVisionBarclayVision 8632 gold badges13 silver badges41 bronze badges 3- 2 Please use jsfiddle to reproduce this behavior. – Josiah Ruddell Commented Apr 22, 2011 at 18:13
- 5 Thats the result of the mathematical expression: 5 / 5 / 2011 = 4.972e-4 sure the string is quoted? – Alex K. Commented Apr 22, 2011 at 18:14
- There has to be more to this, in your example calling myfunction() and passing it a string would just alert the string. Ninja Edit Nice catch Alex, that appears to be what's happening. – Robert Commented Apr 22, 2011 at 18:14
5 Answers
Reset to default 4Thats the result of the mathematical expression: 5 / 5 / 2011 = 4.972e-4
, ensure the string is quoted.
var x = 5/5/2011; //performs division
as opposed to
var x = "5/5/2011"; //creates a string
I had this problem as well (I was passing the string from codebehind on a popup to a javascript on the opener). My solution was pretty simple.
in asp
<asp:Label ID="foo" runat="server"/>
in javascript
foo.Text = "5/5/2011";
in codebehind:
string runThis = "blahblah"
+ "'"
+ foo.Text
+ "';";
Without the single-quote surrounding the text it would spit out the decimal jibberish (ie the mathematical result of 5 / 5 / 2011)
I'm guessing in your situation you could do
alert("'" + myDate + "'");
Try using this syntax:
var mydate = new Date("05/05/2011");
05 divided by 05 divided by 2011 is 0.0004972650422675286, so my guess is it's thinking that 05/05/2011 is an expression not a string. Are you sure there are quotes wrapped around the variable?
0.0004972650422675286 is 5 / 5 / 2011
(as in division).
It is likely you are typing your date without quoting the string, or you are passing the string to eval
when you should be passing it to Date.parse
.