有些时候,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("@[email protected]", YYYY); // format = format.replaceAll("@[email protected]", YY); var M = this.getMonth() + 1; var MM = (M < 10) ? "0" + M : M; // var MMM = mths[M - 1]; // format = format.replaceAll("@[email protected]", MMM); format = format.replaceAll("@[email protected]", MM); format = format.replaceAll("@[email protected]", M); var D = this.getDate(); var DD = (D < 10) ? "0" + D : D; format = format.replaceAll("@[email protected]", DD); format = format.replaceAll("@[email protected]", D); var h = this.getHours(); var hh = (h < 10) ? "0" + h : h; format = format.replaceAll("@[email protected]", hh); format = format.replaceAll("@[email protected]", h); var m = this.getMinutes(); var mm = (m < 10) ? "0" + m : m; format = format.replaceAll("@[email protected]", mm); format = format.replaceAll("@[email protected]", m); var s = this.getSeconds(); var ss = (s < 10) ? "0" + s : s; format = format.replaceAll("@[email protected]", ss); format = format.replaceAll("@[email protected]", s); // var dayOfWeek = this.getDay(); // format = format.replaceAll("@[email protected]", WEEKs[dayOfWeek]); // format = format.replaceAll("@[email protected]", 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("@[email protected]@[email protected]@[email protected] @[email protected]:@[email protected]:@[email protected]"); return date.parseStr("@[email protected]@[email protected]@[email protected]"); }
(4)具体调用:
<button value="日期test" onclick="t1()">dd </button> <button value="时间test" onclick="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>
Ok,搞定了!
时间: 2024-10-30 08:47:25