简体   繁体   中英

javascript convert decimal to 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?

Thats 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.net

<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 + "'");

尝试使用以下语法:

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM