js 날짜와 문자 변환 및 포맷 함수

2775 단어 prototype
<SCRIPT LANGUAGE="JavaScript">
<!--
Date.prototype.format = function(format)   
{   
   var o = {   
     "M+" : this.getMonth()+1, //month   
     "d+" : this.getDate(),    //day   
     "h+" : this.getHours(),   //hour   
     "m+" : this.getMinutes(), //minute   
     "s+" : this.getSeconds(), //second   
     "q+" : Math.floor((this.getMonth()+3)/3), //quarter   
     "S" : this.getMilliseconds() //millisecond   
   }   
   if(/(y+)/.test(format)) format=format.replace(RegExp.$1,   
     (this.getFullYear()+"").substr(4 - RegExp.$1.length));   
   for(var k in o)if(new RegExp("("+ k +")").test(format))   
     format = format.replace(RegExp.$1,   
       RegExp.$1.length==1 ? o[k] :    
         ("00"+ o[k]).substr((""+ o[k]).length));   
   return format;   
} 


function parseDate(str){   

if(typeof str == 'string'){   

var results = str.match(/^ *(\d{4})-(\d{1,2})-(\d{1,2}) *$/);   

if(results && results.length>3)   

return new Date(parseInt(results[1]),parseInt(results[2]) -1,parseInt(results[3]));    

    results = str.match(/^ *(\d{4})-(\d{1,2})-(\d{1,2}) +(\d{1,2}):(\d{1,2}):(\d{1,2}) *$/);   

if(results && results.length>6)   

return new Date(parseInt(results[1]),parseInt(results[2]) -1,parseInt(results[3]),parseInt(results[4]),parseInt(results[5]),parseInt(results[6]));    

    results = str.match(/^ *(\d{4})-(\d{1,2})-(\d{1,2}) +(\d{1,2}):(\d{1,2}):(\d{1,2})\.(\d{1,9}) *$/);   

if(results && results.length>7)   

return new Date(parseInt(results[1]),parseInt(results[2]) -1,parseInt(results[3]),parseInt(results[4]),parseInt(results[5]),parseInt(results[6]),parseInt(results[7]));    

  }   

return null;   

}   

function rain()
{
obj1 = new Date().format("yyyy-MM-dd hh:mm:ss");
obj2 = new Date().format("yyyy-MM-dd");
obj3 = new Date().format("yyyy/MM/dd");
obj4 = new Date().format("MM/dd/yyyy");
obj5 = new Date().format("yyyy-MM-dd hh:mm");
alert("obj1="+obj1+ "/n  obj2="+obj2 +  "/n  obj3="  +obj3+  "/n  obj4="  +obj4);
alert(obj5);
var str = "2010-1-10 22:10:10";
var dates = parseDate(str);
alert(dates.getDate());
obj7 =dates.format("yyyy-MM-dd");
alert(obj7);
}
rain();
//-->
</SCRIPT>

좋은 웹페이지 즐겨찾기