Ibr*_*mer 2 html javascript jquery date-formatting jquery-ui-datepicker
我想根据出生日期计算年龄。我可以轻松地对日期格式 mm/dd/yyyy 执行此操作,但是当我尝试对 dd/mm/yyyy 执行相同操作时,我得到了 Age = NaN。这是我的代码逻辑:
$('#DateOfBirth').datepicker({
onSelect: function (value, ui) {
var today = new Date(),
dob = new Date(value),
age = today.getFullYear() - dob.getFullYear(); //This is the update
$('#age').val(age);
alert(age);
},
//maxDate: "-16Y",
maxDate: maxDateVal,
showOn: "both",
buttonImage: "",
dateFormat: "dd/mm/yy",
changeMonth: true,
changeYear: true,
yearRange: '1920:c'
}).keydown(function (e) {
if (e.keyCode == 8 || e.keyCode == 46) {
$(e.target).val("");
} else {
e.preventDefault();
return false;
}
});
Run Code Online (Sandbox Code Playgroud)
发生这种情况的原因是 new Date(ValueHere) 调用 Date.parse() ,它需要有效的格式。具体参考下文。
正则表达式为您提供的解决方案。
代替:
dob = new Date(value),
Run Code Online (Sandbox Code Playgroud)
使用:(根据您的特定格式进行编辑)
dob = new Date(value.replace(/(\d{2})[-/](\d{2})[-/](\d+)/, "$2/$1/$3"));
Run Code Online (Sandbox Code Playgroud)
一个精简的小提琴来演示解决方案:(针对您的特定格式进行了更新)
http://jsfiddle.net/chrislewispac/e7zjskos/2/
来自: https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
以及: https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
新日期(日期字符串);
日期字符串:
表示日期的字符串值。该字符串应采用 Date.parse() 方法识别的格式(符合 IETF 的 RFC 2822 时间戳以及 ISO8601 的版本)。
日期字符串中的无效值不被识别为 ECMA-262 定义的 ISO 格式,可能会也可能不会导致 NaN,具体取决于浏览器和提供的值。
ECMA-262 日期标准链接:
http://www.ecma-international.org/ecma-262/6.0/index.html#sec-date-time-string-format
并链接到 StackOverflow 解决方案: