87,907
社区成员
发帖
与我相关
我的任务
分享
<html>
<head>
<script type="text/javascript">
String.prototype.toDate = function(){
var format1 = /^\d{4}-\d{1,2}-\d{1,2} \d{2}:\d{2}:\d{2}$/;
var format2 = /^\d{4}-\d{1,2}-\d{1,2}$/;
var date;
if(format1.test(this)){
var strs = this.split(' ');
var str1 = strs[0].split('-');
var str2 = strs[1].split(':');
date = new Date(str1[0],str1[1]-1,str1[2],str2[0],str2[1],str2[2]);
}else if(format2.test(this)){
var strs = this.split('-');
date = new Date(strs[0],strs[1]-1,strs[2]);
}
return date;
}
Date.prototype.format = function(){
var str = this.getYear();
if(this.getMonth() < 9){
str = str + "-0" + (this.getMonth() + 1);
}else{
str = str + "-" + (this.getMonth() + 1);
}
if(this.getDate() < 10){
str = str + "-0" + this.getDate();
}else{
str = str + "-" + this.getDate();
}
str += " ";
if(this.getHours() < 10){
str = str + "0" + this.getHours();
}else{
str = str + this.getHours();
}
if(this.getMinutes() < 10){
str = str + ":0" + this.getMinutes();
}else{
str = str + ":" + this.getMinutes();
}
if(this.getSeconds() < 10){
str = str + ":0" + this.getSeconds();
}else{
str = str + ":" + this.getSeconds();
}
return str;
}
function getDate(){
var str = "2010-3-2";
alert(str.toDate().format());
}
</script>
</head>
<body onload="getDate()">
</body>
</html>
function formatDate(date, format) {
if (!date) return;
if (!format) format = "yyyy-MM-dd";
switch(typeof date) {
case "string":
date = new Date(date.replace(/-/, "/"));
break;
case "number":
date = new Date(date);
break;
}
if (!date instanceof Date) return;
var dict = {
"yyyy": date.getFullYear(),
"M": date.getMonth() + 1,
"d": date.getDate(),
"H": date.getHours(),
"m": date.getMinutes(),
"s": date.getSeconds(),
"MM": ("" + (date.getMonth() + 101)).substr(1),
"dd": ("" + (date.getDate() + 100)).substr(1),
"HH": ("" + (date.getHours() + 100)).substr(1),
"mm": ("" + (date.getMinutes() + 100)).substr(1),
"ss": ("" + (date.getSeconds() + 100)).substr(1)
};
return format.replace(/(yyyy|MM?|dd?|HH?|ss?|mm?)/g, function() {
return dict[arguments[0]];
});
}
alert(formatDate("2010-04-30", "yyyy-MM-dd HH:mm:ss"));
alert(formatDate("2010-04-29 01:00:00", "yyyy-MM-dd HH:mm:ss"));
Number.prototype.pad2 =function(){
return this>9?this:'0'+this;
}
Date.prototype.format=function (format) {
var it=new Date();
var it=this;
var M=it.getMonth()+1,H=it.getHours(),m=it.getMinutes(),d=it.getDate(),s=it.getSeconds();
var n={ 'yyyy': it.getFullYear()
,'MM': M.pad2(),'M': M
,'dd': d.pad2(),'d': d
,'HH': H.pad2(),'H': H
,'mm': m.pad2(),'m': m
,'ss': s.pad2(),'s': s
};
return format.replace(/([a-zA-Z]+)/g,function (s,$1) { return n[$1]; });
}
alert(new Date().format('yyyy-MM-dd HH:mm:ss'));