Convert querstring parameter to javascript date object fails - NaN
I am trying to convert a querystring value into Javascript date object and then converting it into ISO Date format.
I have three button - one extracts the querystring and displays the value - works properly Second, uses first function to extract querystring (works) and then converts to Date - fails - get NaN Third, passes a hardcoded string directly to the second function - works.
Code is shown below. How do I get a querstring value to be converted to Javascript Date
<head>
<SCRIPT LANGUAGE="JavaScript" SRC="./date.format.js">
</SCRIPT>
</head>
<script>
function DateTest(dt)
{
var myDate = new Date(dt);
alert(myDate);
var newDate = myDate.format("isoDateTime");
document.write(newDate);
alert(newDate);
}
function QueryDateTest(parm)
{
DateTest(getRequestParameter(parm));
}
function getRequestParameter( name ) {
var strReturn = "";
var strHref = window.location.href;
if ( strHref.indexOf("?") > -1 ){
var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
var aQueryString = strQueryString.split("&");
for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
if (aQueryString[iParam].indexOf(name.toLowerCase() + "=") > -1 ){
var aParam = aQueryString[iParam].split("=");
strReturn = aParam[1];
break;
}
}
}
alert(unescape(strReturn));
return(unescape(strReturn.toString()));
}
</script>
<body>
<input type="button" id="hello-world1" value="QueryString" onClick="getRequestParameter('create');" />
<input type="button" id="hello-world2" value="ISODate" onClick="QueryDateTest('create');" />
<input type="button" id="hello-world3" value="HardCoded" onClick=开发者_StackOverflow中文版"DateTest('11/10/2009');" />
Works just fine for me in Firefox 3.5 and IE 7. 2 things I can think of, in your query string you might have accidentally typed in a wrong date. Like ll/10/2009 (those are l's like in llama). Then the date would not parse correctly. Second, we would have to see date.format.js and see what its doing to the Date object.
I have your solution. The problem is in your query string, your date has quotes around it, and your query string parser also puts those quotes in the date string. The javascript Date method is very particular about what you pass in, and quotes will make it return a NAN. So here is your easy fix. In your code just make sure you remove the quotes from your date string:
...
alert(unescape(strReturn).replace(/'/gi,""));
return(unescape(strReturn.toString()).replace(/'/gi,""));
}
</script>
精彩评论