Date.prototype.pattern=function(fmt) {
//alert(this.getFullYear());
fmt=fmt.toUpperCase();
var o = {
"MM" : this.getMonth(), //月份
"DD" : this.getDate(), //日
"HH24" : this.getHours(), //小时
"HH" : this.getHours()%12 == 0 ? 12 : this.getHours()%12, //小时
"MI" : this.getMinutes(), //分
"SSS" : this.getMilliseconds(), //毫秒
"SS" : this.getSeconds(), //秒
"QQ" : Math.floor((this.getMonth()+3)/3), //季度
"YYYY":this.getFullYear()<1911?this.getFullYear()+1911:this.getFullYear(), //國際元年
"YYY":this.getFullYear()>1911?this.getFullYear()-1911:this.getFullYear() //台灣民國年
};
//if(/(y+)/.test(fmt)){
// fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
//}
//if(/(E+)/.test(fmt)){
// fmt=fmt.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "/u661f/u671f" : "/u5468") : "")+week[this.getDay()+""]);
//}
for(var k in o){
if(new RegExp("("+ k +")").test(fmt)){
var needLength=RegExp.$1=="HH24"?2:RegExp.$1.length;
//alert("RegExp.$1:"+k +" o[k]:"+o[k].toString().length+" :"+(RegExp.$1.length==o[k].toString().length)+" >"+("00"+ o[k]).substr(-needLength));
fmt = fmt.replace(RegExp.$1, (needLength==o[k].toString().length) ? (o[k]) : (("00"+ o[k]).substr(-needLength)));
}
}
return fmt;
};

String.prototype.toDate=function(){
var year=0,month=0,day=0,hour=0,min=0,sec,mill=0;
var dateflag=false,timeflag=false;
var _value = this.replace(/(^\s*)|(\s*$)/g,"");
//console.log(_value);

var arr=_value.split(/\s/);
if(arr[0])
{
dateflag=true;

var _date=arr[0];
do
{
_date=_date.replace(/[-\/]/,"");

}while(_date.match(/[-\/]/));
if(_date.length!=7&&_date.length!=8)
{
throw 'get the date info is error, ther value is:'+_date;
}
console.log(arr[0]);
year=_date.substring(0,_date.length-4);
month=_date.substring(_date.length-4,_date.length-2);
day=_date.substr(_date.length-2);
console.log("year:"+year +" month:"+month+" day:"+day);

}

if(arr[1])
{
timeflag=true;
console.log(arr[1]);

var _time=arr[1].split(":",3);

hour=_time[0];
min=_time[1];
if(_time[2].indexOf('.')>-1)
{
sec=_time[2].split('.')[0];
mill=_time[2].split('.')[1];
}
else
{
sec=_time[2];
}

console.log("hour:"+hour +" min:"+min+" sec:"+sec+" mill:"+mill);
}


if(dateflag&&!timeflag)
{
var myDate=new Date();
myDate.setFullYear(year);
myDate.setMonth(month);
myDate.setDate(day);
return myDate;
}
else if(dateflag&&timeflag)
{
var myDate=new Date(year,month,day,hour,min,sec);
myDate.setFullYear(year);
myDate.setMonth(month);
myDate.setDate(day);
myDate.setHours(hour);
myDate.setMinutes(min);
myDate.setSeconds(sec);
myDate.setMilliseconds(mill);
return myDate;
}
else
{
throw 'conver string to date have error';
}
}

//var myDate="107-01-01 12:01:01".toDate().pattern();
var myDate="1999-01-01 23:03:04";
document.write(myDate+"<br />")
document.write(myDate.toDate().pattern("YYY-MM-DD HH:MI:SS"));

</script>

posted on 2018-01-11 21:12  阿郎  阅读(490)  评论(0编辑  收藏  举报