Skip to content

Instantly share code, notes, and snippets.

@dmiro
Last active December 17, 2015 07:49
Show Gist options
  • Save dmiro/5576137 to your computer and use it in GitHub Desktop.
Save dmiro/5576137 to your computer and use it in GitHub Desktop.
Date.prototype.format = function(fstr, utc) {
var that = this;
utc = utc ? 'getUTC' : 'get';
return fstr.replace (/%[YmdHMS]/g, function (m) {
switch (m) {
case '%Y': return that[utc + 'FullYear'] ();
case '%m': m = 1 + that[utc + 'Month'] (); break;
case '%d': m = that[utc + 'Date'] (); break;
case '%H': m = that[utc + 'Hours'] (); break;
case '%M': m = that[utc + 'Minutes'] (); break;
case '%S': m = that[utc + 'Seconds'] (); break;
default: return m.slice (1);
}
return ('0' + m).slice (-2);
});
};
@dmiro
Copy link
Author

dmiro commented May 14, 2013

// demo
a = new Date();
console.log(a.format ("%Y-%m-%d %H:%M:%S", true) );
console.log(a.format ("%d/%m/%Y %H:%M:%S", true));
console.log(a.format ("%d/%m/%Y %H:%M:%S", false));
console.log(a.format ("%m", true) ); // formated month
console.log(a.format ("%d", true) ); // formated date

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment