|
Senior Coder
Join Date: Apr 2011
Location: London, England
Posts: 2,120
Thanks: 15
Thanked 354 Times in 353 Posts
|
Prototype that allows for am/pm (or AM/PM) or just a 12-hour clock optional argument:
Code:
Date.prototype.format = function (sFormat, twelve) {
// Returns: A string version of the date.
// Usage: date_instance.format("d mmm yy hh:nn:ss ap") or
// date_instance.format("dddd dd mmmm hh:nn", true)
// Defaults to YYYY/MM/DD.
// twelve == true for a 12hr clock, or just AP or ap within
// sFormat (for AM/PM or am/pm).
var MonthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];
var DayNames = [ "Sunday", "Monday", "Tueday", "Wednesday", "Thursday",
"Friday", "Saturday" ];
var dDate = this || new Date(),
D = dDate.getDate(), DDDD = DayNames[dDate.getDay()],
DDD = DDDD.substr(0,3),
M = dDate.getMonth()+1, MMMM = MonthNames[dDate.getMonth()],
MMM = MMMM.substr(0,3),
YYYY = dDate.getFullYear(), YY = ('' + YYYY).substr(2, 2),
H = dDate.getHours(), N = dDate.getMinutes(), S = dDate.getSeconds(),
ap = (H > 11) ? "pm" : "am",
// pad with leading zeros, if required
DD = ( D < 10 ? "0" : "" ) + D,
MM = ( M < 10 ? "0" : "" ) + M,
NN = ( N < 10 ? "0" : "" ) + N,
SS = ( S < 10 ? "0" : "" ) + S;
var AP = (sFormat && (sFormat.toUpperCase().indexOf('AP')+1)) ?
((sFormat.indexOf('ap')+1) ? ap : ap.toUpperCase()) : '';
if (twelve || AP) {
H = H % 12 || 12;
}
var HH = ( H < 10 ? "0" : "" ) + H;
sFormat = ( sFormat ) ? sFormat.toUpperCase() : 'YYYY/MM/DD';
return sFormat.replace(/D{1,4}|M{1,4}|Y{2,4}|H{1,2}|N{1,2}|S{1,2}|AP/g,
function (m) {
try {
return eval(m);
} catch (e) {
return '';
}
});
};
__________________
"I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
Validate your HTML and CSS
Last edited by AndrewGSW; 09-30-2012 at 01:35 PM..
|