最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript convert decimal to date - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

5 Answers 5

Reset to default 4

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

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

发布评论

评论列表(0)

  1. 暂无评论