I spent a lot of time solving this problem, mainly because the code found on the network is either very cumbersome, or not common, or the format can only be fixed, so I have studied this problem specially, the final optimization is only two lines of code, which is very streamlined. I have been studying the blue ideal for N years. Today, I wrote my own originality for the first time, because I spent a lot of time solving this problem, mainly because the code found on the network is either very cumbersome, either it cannot be general or the format can only be fixed, so I have studied this issue and finally optimized it to only two lines of code, which is very streamlined. JSON, regular expression, and eval functions are mainly used. If you have any questions, please let us know.
Thanks to zhanyuzai for its optimization. After testing the two lines of code, no problem was found. Now it has been updated.
<Html> <body> script /// <summary> /// format the display Date and Time /// </summary> /// <param name = "x"> date and time to be displayed, for example, new Date () </param> // <param name = "y"> the format to be displayed, for example, yyyy-MM-dd hh: mm: ss </param> function date2str (x, y) {var z = {y: x. getFullYear (), M: x. getMonth () + 1, d: x. getDate (), h: x. getHours (), m: x. getMinutes (), s: x. getSeconds ()}; return y. replace (/(y + | M + | d + | h + | m + | s +)/g, function (v) {return (v. length> 1? "0": "") + eval ('z. '+ v. slice (-1). slice (-(v. length> 2? V. length: 2)});} alert (date2str (new Date (), "yyyy-M-d h: m: s ")); alert (date2str (new Date (), "yy-MMMM-d h: m: s"); script </body> </ptml>
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]