Format the date in js
Sometimes, the date in js is displayed in the format of yyyy/MM/dd, but I need the format of yyyy-MM-dd
Simple and crude direct replace is always not good, or it is still a little rough to splice it through the related methods of the Date object.
If it can be formatted,
I collected some information on the Internet, modified and debugged it to make it available. OK, the following code:
(1) The formatting method of date Data needs to be expanded first.
// Extended Date formatting method 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) because the string. replaceAll method is used, this is also a string extension:
String.prototype.replaceAll = function (s1, s2) { return this.replace(new RegExp(s1, "gm"), s2);}
(3) write the formatting method:
// Date Formatting 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) specific call:
Dd<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!