js 日期和Date的相互转换

//日期  /.-转Date  Date转/.-默认-
function StringToDate(DateStr)  { 
	var separator="-";
	if(DateStr.indexOf("/")>-1)separator="/";
	if(DateStr.indexOf(".")>-1)separator=".";
    var converted = Date.parse(DateStr);  
    var myDate = new Date(converted);  
    if (isNaN(myDate)){   
        var arys= DateStr.split(separator);  
        myDate = new Date(arys[0],arys[1]-1,arys[2]);  //人类的习惯 month就是几月
    }  
    return myDate;  
}
function DateToString(date,separatorStr){
	var separator="-";
	if(separatorStr)separator=separatorStr;
	if(typeof date=="string")date=StringToDate(date);
	return date.getFullYear()+separator+(date.getMonth()+1)+separator+date.getDate();
}
console.log(StringToDate("2012-03-09"));
console.log(StringToDate("2012-3-9"));
console.log(StringToDate("2012/3/9"));
console.log(StringToDate("2012.03.09"));
console.log(DateToString(new Date()));
console.log(DateToString("2012-03-09","."));

posted @ 2012-03-10 10:05  xngeer  阅读(1120)  评论(0编辑  收藏  举报