Original: JavaScript's date format, which mimics the format of the date command in the shell
The current date is displayed in the shell
[[email protected]]$ date '+%Y-%m-%d %H:%M:%S'2015-01-19 16:24:58
It is inconvenient to format the date object in JavaScript into a suitable string, simulating the format in the shell
Let's start with a simple 3-paragraph code to illustrate the features used in the simulation function.
Replace of string
var a = '1234'undefineda.replace('1', 'ab') "ab234"a"1234"b = a.replace('1', 'ab') "ab234"b"ab234"
Note:replace returns the replacement result instead of changing it directly in the string
function of date
d = new Date();Mon Jan 19 2015 17:08:04 GMT+0800 (中国标准时间)d.getFullYear()2015d.getMonth()0d.getDate()19d.getHours()17d.getMinutes()8d.getSeconds()4// 单位是毫秒d.getTime()1421658484111
Pay attention to the units of GetTime
Regular match
fmt = '%Y-%m-%d'"%Y-%m-%d"// 要特别注意其中的括号/(%Y)/.test(fmt)trueRegExp.$1"%Y"/%Y/.test(fmt)trueRegExp.$1""// return替换后的结果, 而不是直接替换fmtfmt.replace(RegExp.$1, 'abc')"abc-%m-%d"/(Y/.test(fmt)
Code for impersonation
Chrome Press F12, open drawer Test Date.prototype.format = function (FMT) {//author:meizz var o = {"%m": This.getmont H () +1+ ",//month"%d ": this.getdate () +",//Day "%H": this.gethours () + ", Hours "%M": this.getminutes () + ",//min"%s ": this.getseconds () +", SEC//"q+": Math.floor ((This.getmonth () +3)/3),//quarterly}; Year if (/(%Y)/.test (FMT)) Fmt=fmt.replace (Regexp.$1, (this.getfullyear () + "")); Two-bit year%y (/()/.test (FMT)) Fmt=fmt.replace (Regexp.$1, (this.getfullyear () + ""). substr (2)); GetTime is returned in milliseconds, converted to seconds if (/(%s)/.test (FMT))//fmt=fmt.replace (regexp.$1, This.gettime ()/1000); Fmt=fmt.replace (Regexp.$1, (this.gettime () + "). Slice (0, 10)); For (var k in O) if (New RegExp ("(" + K +) "). Test (FMT)) {FMT = Fmt.replace (regexp.$1, (o[k].length = = 2? o[ K]: ' 0 ' + o[k]); } return FMT; } > D = new DAte ();< Mon Jan 16:54:46 gmt+0800 (China Standard Time) > D.format ('%y-%m-%d%h:%m:%s ') < "2015-01-19 16:54:46" > D.fo Rmat ('%s ') < "1421657686"
If you want to use the formal environment, you can put the above function, put in a JS file, and then reference in the HTML file
The date format of JavaScript, mimicking the format of the date command in the shell