<SCRIPT LANGUAGE="JavaScript">
String.prototype.toDate = function(style){ 
var y = this.substring(style.indexOf('y'),style.lastIndexOf('y')+1);//年 
var m = this.substring(style.indexOf('M'),style.lastIndexOf('M')+1);//月 
var d = this.substring(style.indexOf('d'),style.lastIndexOf('d')+1);//日 
if(isNaN(y)) y = new Date().getFullYear(); 
if(isNaN(m)) m = new Date().getMonth(); 
if(isNaN(d)) d = new Date().getDate(); 
alert(m)
var dt ; 
eval ("dt = new Date('"+ y+"', '"+(m-1)+"','"+ d +"')"); 
return dt; 
} alert("20081009".toDate("yyyyMMdd"))
alert("200829".toDate("yyyyMd"))
</SCRIPT>String.prototype.toDate = function(style){}
其实是类似于function toDate(style){}
只不过这个toDate函数只能作用于string类型变量

解决方案 »

  1.   

    通过prototype可以定义对象的自定义方法
    LZ提到的方法对String进行了扩展,对日期格式的String进行转换,style就是日期格式,例如:
    var test = "2008-11-16";   
    var res = test.toDate("yyyy-MM-dd");
    alert("res="+res);
      

  2.   

    1、是一个自定义的方法toDate;function(style)是带参的函数对象(方法的具体实现)。
    2、引用:
    <script type="text/javascript"> 
    <!--
    String.prototype.toDate = function(style){
    var y = this.substring(style.indexOf('y'),style.lastIndexOf('y')+1);//年
    var m = this.substring(style.indexOf('M'),style.lastIndexOf('M')+1);//月
    var d = this.substring(style.indexOf('d'),style.lastIndexOf('d')+1);//日
    if(isNaN(y)) y = new Date().getFullYear();
    if(isNaN(m)) m = new Date().getMonth();
    if(isNaN(d)) d = new Date().getDate();
    var dt ;
    eval ("dt = new Date('"+ y+"', '"+(m-1)+"','"+ d +"')");
    return dt;
    }
    var s='2008-11-15';
    alert(s.toDate('yyyy-MM-dd'))
    //--> 
    </script>