Date formatter with easy-to-remember format specifiers:
function formatDate(date, fmt) {
return fmt.replace(
/\{([^}:]+)(?::(\d+))?\}/g,
function (s, comp, pad) {
var fn = date["get" + comp];
if (fn) {
var v = (fn.call(date) +
(/Month$/.test(comp) ? 1 : 0)).toString();
return pad && (pad = pad - v.length)
? new Array(pad + 1).join("0") + v
: v;
} else {
return s;
}
});
};
Whatever you enclose inside curly brackets will be used as a format specifier:
var now = new Date();
alert(formatDate(now, "This is the year {FullYear}"));
// Output: This is the year 2008
You can also zero-pad values:
alert(formatDate(now, "{FullYear}-{Month:2}-{Date:2}"));
// Output: 2008-09-02
alert(formatDate(now, "{Hours:2}:{Minutes:2}:{Seconds:2}.{Milliseconds:3}"));
// Output: 15:47:32.156
If an unknown format specifier is used, the format specifier will be used as it is:
alert(formatDate(now, "{Hourz} hours {Minutes} minutes"));
// Output: {Hourz} hours 51 minutes
Invalid format specifiers are also handled gracefully:
alert(formatDate(now, "{FullYear:}));
// Output: {FullYear:}
All Date instance getters are recognized as valid format specifiers.