这是我的 HTML
<input type="text" class="dateofbirthpicker">
<input type="text" id="usia">
脚本
$(function() {
$('.dateofbirthpicker').datepicker({
dateFormat: 'yyyy/mm/dd'
});
});
window.onload=function() {
$('.dateofbirthpicker').on('change', function() {
var dob = new Date(this.value);
var today = new Date();
var age = Math.floor((today-dob) / (1000 * 60 * 60 * 24 * 360));
ages = parseInt(age);
$('#usia').val(ages);
});
}
我有上面的脚本来计算从日期开始的年龄。它在Firefox中返回年龄,但在Chrome中返回NaN
。
我这样做Jquery Date.parse returning NaN in Chrome browser?
当我运行以下内容时结果为无效日期...
var dob = new Date(this.value);
答案 0 :(得分:2)
将日期格式更改为dateFormat: 'yy/mm/dd'
来自specs,
$(function() {
$('.dateofbirthpicker').datepicker({
dateFormat: 'yy/mm/dd',
onSelect: function() {
var dob = new Date(this.value);
var today = new Date();
var age = Math.floor((today - dob) / (1000 * 60 * 60 * 24 * 360));
ages = parseInt(age);
$('#usia').val(ages);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.8.18/jquery-ui.min.js"></script>
<link href="http://code.jquery.com/ui/1.8.21/themes/base/jquery-ui.css" rel="stylesheet" />
<input type="text" class="dateofbirthpicker">
<input type="text" id="usia">
答案 1 :(得分:0)
感谢大家的讨论和建议..我从这里得到答案 New Date() returns invalid date
$(function() {
$('.dateofbirthpicker').datepicker({
dateFormat: 'dd/mm/yy'
});
});
window.onload=function(){
$('.dateofbirthpicker').on('change', function() {
var dselect = $(".dateofbirthpicker").val();
var match = /(\d+)\/(\d+)\/(\d+)/.exec(dselect);
var dob = new Date(match[3], match[2], match[1]);
var today = new Date();
var age = Math.floor((today-dob) / (1000 * 60 * 60 * 24 * 360));
$('#usia').val(age);
});
}