Created
August 7, 2014 12:39
-
-
Save 9point6/280ea478659bbf2bceb3 to your computer and use it in GitHub Desktop.
Localised month/weekday name and ordinal functions for the Javascript Date object
This file contains hidden or 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
# Just add new languages to this object | |
Date.locale = | |
'en': | |
'months': ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] | |
'days': ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] | |
'ordinals': ['th', 'st', 'nd', 'rd'] | |
# Get current locale | |
Date.prototype.getLocale = ( lang ) -> | |
Date.locale[lang] ? Date.locale['en'] | |
# Make month and day functions | |
for period in ['Month', 'Day'] | |
do ( period ) -> | |
current = "get#{period}Name" | |
# Long [month/day] name | |
Date.prototype[current] = ( lang ) -> | |
@getLocale( lang )["#{period.toLowerCase( )}s"][@["get#{period}"]( )] | |
# Short [month/day] name | |
Date.prototype["#{current}Short"] = ( lang ) -> | |
@[current]( lang ).substr 0, 3 | |
# Gets the day of the month with "th", etc on the end | |
Date.prototype.getDateOrdinal = ( lang ) -> | |
ordinals = @getLocale( lang ).ordinals | |
date = @getDate( ) | |
date + ( ordinals[(date - 20) % 10] or ordinals[date] or ordinals[0] ) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment