The simplest and most flexible javascript date-to-string tool functions I have ever seen
We know that the Date object in javascript does not provide a Date Formatting Function. Converting a Date object to a format like 20:35:11 is a common requirement in projects. I recently saw a piece of code in our project, which is very short and shared here.
Date. prototype. format = function (format) {var o = {M +: this. getMonth () + 1, // monthd +: this. getDate (), // dayh +: this. getHours (), // hourm +: this. getMinutes (), // minutes +: this. getSeconds () // second}; if (/(y + )/. test (format) {format = format. replace (RegExp. $1, (this. getFullYear () + ). substr (4-RegExp. $1. length);} for (var k in o) {if (new RegExp (+ k + )). test (format) {format = format. replac E (RegExp. $1, RegExp. $1. length = 1? O [k]: (00 + o [k]). substr (+ o [k]). length) ;}} return format ;};
This Code supports regular expressions, so we can flexibly create date formatting strings:
Var date = new Date (); alert (date. format (yyyy-MM -- dd hh: mm: ss ));