有些時候,js中日期顯示出來是 yyyy/MM/dd 這種格式,但是我需要yyyy-MM-dd格式的
簡單粗暴的直接replace總是不太好,或者通過Date對象的相關方法拼接起來,也還是有些粗暴
要是可以格式化就好了,
在網上收集了一些資料,經過修改調試,完成可用,OK,以下的代碼:
(1)首先需要擴展日期Data的格式化方法
//擴展日期格式化方法
Date.prototype.parseStr = function (format) {
var YYYY = this.getFullYear(); //2011
// var YY = YYYY.substring(2); // 11
format = format.replaceAll("@YYYY@", YYYY);
// format = format.replaceAll("@YY@", YY);
var M = this.getMonth() + 1;
var MM = (M < 10) ? "0" + M : M;
// var MMM = mths[M - 1];
// format = format.replaceAll("@MMM@", MMM);
format = format.replaceAll("@MM@", MM);
format = format.replaceAll("@M@", M);
var D = this.getDate();
var DD = (D < 10) ? "0" + D : D;
format = format.replaceAll("@DD@", DD);
format = format.replaceAll("@D@", D);
var h = this.getHours();
var hh = (h < 10) ? "0" + h : h;
format = format.replaceAll("@hh@", hh);
format = format.replaceAll("@h@", h);
var m = this.getMinutes();
var mm = (m < 10) ? "0" + m : m;
format = format.replaceAll("@mm@", mm);
format = format.replaceAll("@m@", m);
var s = this.getSeconds();
var ss = (s < 10) ? "0" + s : s;
format = format.replaceAll("@ss@", ss);
format = format.replaceAll("@s@", s);
// var dayOfWeek = this.getDay();
// format = format.replaceAll("@WEEK@", WEEKs[dayOfWeek]);
// format = format.replaceAll("@WEK@", WEKs[dayOfWeek]);
return format;
}
(2)由於用到了string.replaceAll方式,這個也是string的擴展:
String.prototype.replaceAll = function (s1, s2) {
return this.replace(new RegExp(s1, "gm"), s2);
}
(3)寫出格式化方法:
//日期格式化
function parseDate(dateStr, hasTime) {
var date = new Date(dateStr.replace(/-/g, "/"));
if (hasTime)
return date.parseStr("@YYYY@-@MM@-@DD@ @hh@:@mm@:@ss@");
return date.parseStr("@YYYY@-@MM@-@DD@");
}
(4)具體調用:
<button value="日期test" οnclick="t1()">dd
</button>
<button value="時間test" οnclick="t2()">
</button>
<script>
function t1() {
var str = "2015/5/8";
alert(parseDate(str, false));
}
function t2() {
var str = "2015/5/8 10:01:02";
alert(parseDate(str, true));
}
</script>