Skip to content

Instantly share code, notes, and snippets.

@lstebner
Created May 16, 2012 00:06
Show Gist options
  • Save lstebner/2706168 to your computer and use it in GitHub Desktop.
Save lstebner/2706168 to your computer and use it in GitHub Desktop.
JavaScript Date Format Using PHP Wildcards
Date.format = function(d, format, custom_months, custom_days){
var months = custom_months || ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
,days = custom_days || ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
,replacements = [
//day
[ '%d', (d.getDate() < 10 ? '0' : '') + d.getDate() ] //leading 0: 01-31
, [ '%D', days[ d.getDay() ].substr(0, 3) ] //3 letter representation (Mon-Sun)
, [ '%j', d.getDate() ] //no leading 0: 1-31
, [ '%l', days[ d.getDay() ] ] //[lowercase L], full textual representation (Monday-Sunday)
, [ '%N', (d.getDay() + 1) ] //day #: 1-7 (1=monday, 7=sunday)
//month
, [ '%F', months[ d.getMonth() ] ] //full textual representation (January-December)
, [ '%m', (d.getMonth() < 10 ? '0' : '') + (d.getMonth() + 1) ] //leading 0: 01-12
, [ '%M', months[ d.getMonth() ].substr(0, 3) ] //3 letter represenation (Jan-Dec)
, [ '%n', (d.getMonth() + 1) ] //no leading 0: 1-12
//year
, [ '%Y', d.getFullYear() ] //4 digits
, [ '%y', d.getFullYear().toString().substr(2) ] //2 digits
//hour
, [ '%g', (d.getHours() % 12 == 0 ? 12 : d.getHours() % 12) ] //12 hour, without leading 0: 1-12
, [ '%G', (d.getHours() == 0 ? '00' : d.getHours()) ] //24 hour, without leading 0: 1-24
, [ '%h', (d.getHours() % 12 == 0 ? 12 : (d.getHours() < 10 ? '0' : '') ) + (d.getHours() % 12) ] //12 hour, leading 0: 01-12
, [ '%H', (d.getHours() == 0 ? 12 : (d.getHours() < 10 ? '0' : '')) + (d.getHours()) ] //24 hour, leading 0: 01-24
//minute
, [ '%i', (d.getMinutes() < 10 ? '0' : '') + d.getMinutes() ] //with leading 0: 00-59
//second
, [ '%s', (d.getSeconds() < 10 ? '0' : '') + d.getSeconds() ] //with leading 0: 00-59
//ampm
, [ '%a', (d.getHours() < 12 ? 'am' : 'pm') ] //lowercase
, [ '%A', (d.getHours() < 12 ? 'AM' : 'PM') ] //uppercase
]
,i = null
;
for (i in replacements){
format = format.replace( replacements[i][0], replacements[i][1] );
}
return format;
}
@jeremyckahn
Copy link

Attaching things to standard host Objects is risky; 3rd party code may overwrite your static property on Date.

@lstebner
Copy link
Author

Well, I kind of am that 3rd party selfishly overriding "Date.format"...but it's a fair point to be aware of if in a less controlled environment simply calling this date_format instead is probably a good idea.

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