我已经提出了这个解决方案来扩展JavaScript的Date.parse
函数以允许格式化为DD / MM / YYYY的日期(而不是美国标准[和默认] MM / DD / YYYY):
(function() {
var fDateParse = Date.parse;
Date.parse = function(sDateString) {
var a_sLanguage = ['en','en-us'],
a_sMatches = null,
sCurrentLanguage,
dReturn = null,
i
;
//#### Traverse the a_sLanguages (as reported by the browser)
for (i = 0; i < a_sLanguage.length; i++) {
//#### Collect the .toLowerCase'd sCurrentLanguage for this loop
sCurrentLanguage = (a_sLanguage[i] + '').toLowerCase();
//#### If this is the first English definition
if (sCurrentLanguage.indexOf('en') == 0) {
//#### If this is a definition for a non-American based English (meaning dates are "DD MM YYYY")
if (sCurrentLanguage.indexOf('en-us') == -1 && // en-us = English (United States) + Palau, Micronesia
sCurrentLanguage.indexOf('en-ca') == -1 && // en-ca = English (Canada)
sCurrentLanguage.indexOf('en-ph') == -1 && // en-ph = English (Philippians)
sCurrentLanguage.indexOf('en-bz') == -1 // en-bz = English (Belize)
) {
//#### Setup a oRegEx to locate "## ## ####" (allowing for any sort of delimiter except a '\n') then collect the a_sMatches from the passed sDateString
var oRegEx = new RegExp("(([0-9]{2}|[0-9]{1})[^0-9]*?([0-9]{2}|[0-9]{1})[^0-9]*?([0-9]{4}))", "i");
a_sMatches = oRegEx.exec(sDateString);
}
//#### Fall from the loop (as we've found the first English definition)
break;
}
}
//#### If we were able to find a_sMatches for a non-American English "DD MM YYYY" formatted date
if (a_sMatches != null) {
var oRegEx = new RegExp(a_sMatches[0], "i");
//#### .parse the sDateString via the normal Date.parse function, but replacing the "DD?MM?YYYY" with "YYYY/MM/DD" beforehand
//#### NOTE: a_sMatches[0]=[Default]; a_sMatches[1]=DD?MM?YYYY; a_sMatches[2]=DD; a_sMatches[3]=MM; a_sMatches[4]=YYYY
dReturn = fDateParse(sDateString.replace(oRegEx, a_sMatches[4] + "/" + a_sMatches[3] + "/" + a_sMatches[2]));
}
//#### Else .parse the sDateString via the normal Date.parse function
else {
dReturn = fDateParse(sDateString);
}
//####
return dReturn;
}
})();
在我的实际(dotNet)代码中,我通过以下方式收集a_sLanguage数组:
a_sLanguage = '<% Response.Write(Request.ServerVariables["HTTP_ACCEPT_LANGUAGE"]); %>'.split(',');
现在,我不确定我找到“us-en”等的方法。是最合适的。几乎只有美国和当前/以前美国影响的地区(帕劳,密克罗尼西亚,菲律宾)+伯利兹&amp;加拿大使用时髦的MM / DD / YYYY格式(我是美国人,所以我可以称之为funky =)。因此,如果Locale不是“en-us”/ etc,那么可以正确地争辩说。首先,应该使用DD / MM / YYYY。想法?
作为旁注......我在PERL中“长大”,但是自从我在RegEx中做了很多繁重的工作以来,这一直都很小。这个表达对每个人来说都是正确的吗?
这似乎很多工作,但根据我的研究,这确实是关于在JavaScript中启用DD / MM / YYYY日期的最佳方式。有更轻松/更好的方式吗?
PS-在提交之前重新阅读这篇文章...我已经意识到这更像是“你可以代码审查这个”而不是一个问题(或者,答案是嵌入在题)。当我开始写这篇文章时,我不打算在这里结束=)