Created
January 8, 2010 01:34
-
-
Save stephenlb/271789 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* ---------------------------------------------------------------------------- | |
JavaScript Easy Date Function Similar to PHP but with JS Function Names minus 'get' | |
"Today is Thursday the 7th in January 2010. The time is 5:28pm and 46 Seconds." | |
jsdate( | |
'Today is {Day} the {Date}{DateSuffix} in {Month} {FullYear}. ' + | |
'The time is {HalfHours}:{Minutes}{AMPM} and {Seconds} Seconds.' | |
); | |
Refer to http://www.w3schools.com/jsref/jsref_obj_date.asp | |
---------------------------------------------------------------------------- */ | |
// Minified (709 bytes) | |
var jsdate=function(){var e=/{(\w+)}/g,f="th,st,nd,rd,th,th,th,th,th,th".split(","),g="Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday".split(","),h="January,February,March,April,May,June,July,August,September,October,November,December".split(",");return function(d,a){d=d||"";a=a||new Date;a.d=a.getDay;a.getDay=function(){return g[a.d()]};a.m=a.getMonth;a.getMonth=function(){return h[a.m()]};a.getHalfHours=function(){var b=a.getHours();if(b===0)return 12;return b>13?b-12:b};a.getAMPM=function(){return a.getHours()> | |
11?"pm":"am"};a.getDateSuffix=function(){var b=a.getDate();return f[b>9&&b<20?0:b.toString().slice(-1)]};return d.replace(e,function(b,c){c="get"+c;return a[c]&&a[c]()||""})}}(); | |
// Source Non-minified (2.2KB) | |
var jsdate = (function(){ | |
var rx = /{(\w+)}/g | |
, suffix = 'th,st,nd,rd,th,th,th,th,th,th'.split(',') | |
, doweek = 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(',') | |
, month = 'January,February,March,April,May,June,July,August,September,October,November,December'.split(','); | |
return function( str, date ) { | |
str = str || ''; | |
date = date || new Date; | |
date.d = date.getDay; | |
date.getDay = function(){ return doweek[date.d()] }; | |
date.m = date.getMonth; | |
date.getMonth = function(){ return month[date.m()] }; | |
date.getHalfHours = function(){ | |
var hours = date.getHours(); | |
if (hours === 0) return 12; | |
return hours > 13 ? hours - 12 : hours | |
}; | |
date.getAMPM = function(){ return date.getHours() > 11 ? 'pm' : 'am' }; | |
date.getDateSuffix = function(){ | |
var day = date.getDate(); | |
return suffix[day > 9 && day < 20 ? 0 : day.toString().slice(-1)] | |
}; | |
return str.replace( rx, function( _, key ) { key = 'get' + key; | |
return date[key] && date[key] () || '' | |
} ) | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment