本文介绍了jQuery年龄计算日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在以下jQuery代码中缺少什么吗?
Am I missing something in the following jQuery code?
var dob = $('#date').val();
if(dob != ''){
var today = new Date();
var dayDiff = Math.ceil(today - dob) / (1000 * 60 * 60 * 24 * 365);
var age = parseInt(dayDiff);
$('#age').html(age+' years old');
}
我正在从MySQL数据库中获取#date的预取值.
I am getting the pre-fetched value of #date from MySQL db.
<input type="text" value="1988-04-07" id="#date" name="dob" /><p id="age"></p>
它返回的是NaN,而不是正确的值.
It's returning NaN, not the correct value.
推荐答案
$('#date').val()
返回字符串'1988-04-07'
.您需要将其解析为实际数字.
$('#date').val()
returns the string '1988-04-07'
. You need to parse it into an actual number.
dob = new Date(dob);
var today = new Date();
var age = Math.floor((today-dob) / (365.25 * 24 * 60 * 60 * 1000));
$('#age').html(age+' years old');
正如@esqew指出的那样,您还需要将id="#date"
更改为id="date"
.
As @esqew points out, you also need to change id="#date"
to id="date"
.
这篇关于jQuery年龄计算日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!