我已经提出了一个扩展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"/etc的方法是最合适的。几乎只有美国和当前/前美国影响地区(帕劳、密克罗尼西亚、菲律宾)+伯利兹和加拿大使用时髦的MM/DD/YYYY格式(我是美国人,所以我可以称之为funky =)。因此,如果区域设置不是"en-us"/etc,那么首先应该使用DD/MM/YYYY。有什么想法?
作为旁注..。我是在PERL中“成长”的,但自从我在RegEx中做了很多繁重的工作以来,已经有一段时间了。这句话对每个人来说都是正确的吗?
这似乎是很多工作,但根据我的研究,这确实是在JavaScript中启用DD/MM/YYYY日期的最佳方法。有没有更容易[更好]的方法?
在重新阅读这篇文章之前.我已经意识到,这更像是一个“您可以对此进行代码检查”,而不是一个问题(或者,问题中嵌入了一个答案)。当我开始写这篇文章的时候,我并不想在这里结束
发布于 2010-06-09 05:56:40
我会用达特杰。您可以直接加载适合于给定ISO语言代码的版本(例如日期-en-CA.js或日期-en-GB.js)。只有大写是不同的。
https://stackoverflow.com/questions/3003355
复制相似问题