Skip to content

Instantly share code, notes, and snippets.

@zackthehuman
Created January 25, 2012 17:21
Show Gist options
  • Save zackthehuman/1677420 to your computer and use it in GitHub Desktop.
Save zackthehuman/1677420 to your computer and use it in GitHub Desktop.
Locale-based short date formatting
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()));
@zackthehuman
Copy link
Author

Most of the function came from this SO answer: http://stackoverflow.com/a/3187610/18265.

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