在我的应用程序中,我需要计算此人的年龄,我将获得当前日期和他们的生日(以毫秒为单位)。计算日期的差异并将其转换为年份
$scope.getAge=function(birthday){
if (birthday!=undefined&&birthday!="") {
var date = birthday.split('-');
var currentDate = new Date();
var convertedBD= new Date(date[1]+"-"+date[0]+"-"+date[2]);
var diff = Math.abs(currentDate-convertedBD)/(1000*60*60*24*365);
return Math.round(diff);
}
else {
return "0";
}}
这适用于谷歌浏览器中的桌面浏览器和移动预览,但当我在真实移动设备上测试它时,它会显示每个值的NaN。我无法弄清楚问题是什么。
答案 0 :(得分:1)
尝试.getTime(),它明确要求Date的毫秒部分:
var diff = Math.abs(currentDate.getTime() - convertedBD.getTime())/(1000*60*60*24*365);
尝试使用此解析:
if (birthday!=undefined&&birthday!="") {
var date = birthday.split('-');
var currentDate = new Date();
var convertedBD= new Date( parseInt(date[2]), parseInt(date[1]), parseInt(date[0]) );
var diff = Math.abs(currentDate-convertedBD)/(1000*60*60*24*365);
return Math.round(diff);
}