Created
January 25, 2012 17:21
-
-
Save zackthehuman/1677420 to your computer and use it in GitHub Desktop.
Locale-based short date formatting
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
var getShortDateFormat = (function() { | |
var pattern = undefined, | |
defaultPattern = "M/d/yyyy", | |
localeFormatMappings = { | |
"en-us": "M/d/yyyy", | |
"ja-jp": "yyyy\u5E74 M\u6708 d\u65E5" | |
}; | |
return function(date, locale) { | |
var m, d, y; | |
locale = locale || ""; | |
locale = locale.toLowerCase(); | |
pattern = localeFormatMappings[locale] || defaultPattern; | |
return pattern.replace('yyyy', y = '' + date.getFullYear()) | |
.replace('yy', y.substring(2)) | |
.replace('MM', zeroPad(m = date.getMonth() + 1)) | |
.replace('M', m) | |
.replace('dd', zeroPad(d = date.getDate())) | |
.replace('d', d); | |
} | |
function zeroPad(n) { | |
return (+n < 10 ? '0' : '') + n; | |
} | |
})(); | |
alert(getShortDateFormat(new Date(), "en-US")); | |
alert(getShortDateFormat(new Date(), "ja-jp")); | |
alert(getShortDateFormat(new Date())); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Most of the function came from this SO answer: http://stackoverflow.com/a/3187610/18265.