Skip to content

Instantly share code, notes, and snippets.

@thomaspuppe
Created September 25, 2014 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomaspuppe/6a4bd1d014bb04194f97 to your computer and use it in GitHub Desktop.
Save thomaspuppe/6a4bd1d014bb04194f97 to your computer and use it in GitHub Desktop.
Format a JS Date Object according toa given String
/* *****************************************************************************
* Formates a JS Date Object according toa given String. The Place holders
* work like the php date() function, but not every case is implemented !
*
* %d% Day of the month, 2 digits with leading zeros
* %j% Day of the month without leading zeros
* %m% Numeric representation of a month, with leading zeros
* %n% Numeric representation of a month, without leading zeros
* %Y% A full numeric representation of a year, 4 digits
* %y% A two digit representation of a year
* %G% 24-hour format of an hour without leading zeros
* %H% 24-hour format of an hour with leading zeros
* %i% Minutes with leading zeros
* %s% Seconds, with leading zeros
* ************************************************************************** */
var formatDateObject = function (dateObject, formatString) {
"use strict";
var j = String(dateObject.getDate()),
d = String((j.length===1) ? "0"+j : j),
n = String(dateObject.getMonth()+1),
m = String((n.length===1) ? "0"+n : n),
y = String(dateObject.getYear()).substr(-2, 2),
Y = String(dateObject.getFullYear()),
G = String(dateObject.getHours()),
H = String((G.length===1) ? "0"+G : G),
i = String(dateObject.getMinutes()),
s = String(dateObject.getSeconds());
return formatString.replace('%j%', j)
.replace(/%d%/g, d)
.replace(/%n%/g, n)
.replace(/%m%/g, m)
.replace(/%y%/g, y)
.replace(/%Y%/g, Y)
.replace(/%G%/g, G)
.replace(/%H%/g, H)
.replace(/%i%/g, i)
.replace(/%s%/g, s);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment